Merge branch 'timers-core-for-linus' of git://git.kernel.org/pub/scm/linux/kernel...
[linux-2.6-block.git] / kernel / time / posix-timers.c
1 /*
2  * linux/kernel/posix-timers.c
3  *
4  *
5  * 2002-10-15  Posix Clocks & timers
6  *                           by George Anzinger george@mvista.com
7  *
8  *                           Copyright (C) 2002 2003 by MontaVista Software.
9  *
10  * 2004-06-01  Fix CLOCK_REALTIME clock/timer TIMER_ABSTIME bug.
11  *                           Copyright (C) 2004 Boris Hu
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or (at
16  * your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful, but
19  * WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21  * General Public License for more details.
22
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26  *
27  * MontaVista Software | 1237 East Arques Avenue | Sunnyvale | CA 94085 | USA
28  */
29
30 /* These are all the functions necessary to implement
31  * POSIX clocks & timers
32  */
33 #include <linux/mm.h>
34 #include <linux/interrupt.h>
35 #include <linux/slab.h>
36 #include <linux/time.h>
37 #include <linux/mutex.h>
38 #include <linux/sched/task.h>
39
40 #include <linux/uaccess.h>
41 #include <linux/list.h>
42 #include <linux/init.h>
43 #include <linux/compiler.h>
44 #include <linux/hash.h>
45 #include <linux/posix-clock.h>
46 #include <linux/posix-timers.h>
47 #include <linux/syscalls.h>
48 #include <linux/wait.h>
49 #include <linux/workqueue.h>
50 #include <linux/export.h>
51 #include <linux/hashtable.h>
52 #include <linux/compat.h>
53 #include <linux/nospec.h>
54
55 #include "timekeeping.h"
56 #include "posix-timers.h"
57
58 /*
59  * Management arrays for POSIX timers. Timers are now kept in static hash table
60  * with 512 entries.
61  * Timer ids are allocated by local routine, which selects proper hash head by
62  * key, constructed from current->signal address and per signal struct counter.
63  * This keeps timer ids unique per process, but now they can intersect between
64  * processes.
65  */
66
67 /*
68  * Lets keep our timers in a slab cache :-)
69  */
70 static struct kmem_cache *posix_timers_cache;
71
72 static DEFINE_HASHTABLE(posix_timers_hashtable, 9);
73 static DEFINE_SPINLOCK(hash_lock);
74
75 static const struct k_clock * const posix_clocks[];
76 static const struct k_clock *clockid_to_kclock(const clockid_t id);
77 static const struct k_clock clock_realtime, clock_monotonic;
78
79 /*
80  * we assume that the new SIGEV_THREAD_ID shares no bits with the other
81  * SIGEV values.  Here we put out an error if this assumption fails.
82  */
83 #if SIGEV_THREAD_ID != (SIGEV_THREAD_ID & \
84                        ~(SIGEV_SIGNAL | SIGEV_NONE | SIGEV_THREAD))
85 #error "SIGEV_THREAD_ID must not share bit with other SIGEV values!"
86 #endif
87
88 /*
89  * The timer ID is turned into a timer address by idr_find().
90  * Verifying a valid ID consists of:
91  *
92  * a) checking that idr_find() returns other than -1.
93  * b) checking that the timer id matches the one in the timer itself.
94  * c) that the timer owner is in the callers thread group.
95  */
96
97 /*
98  * CLOCKs: The POSIX standard calls for a couple of clocks and allows us
99  *          to implement others.  This structure defines the various
100  *          clocks.
101  *
102  * RESOLUTION: Clock resolution is used to round up timer and interval
103  *          times, NOT to report clock times, which are reported with as
104  *          much resolution as the system can muster.  In some cases this
105  *          resolution may depend on the underlying clock hardware and
106  *          may not be quantifiable until run time, and only then is the
107  *          necessary code is written.  The standard says we should say
108  *          something about this issue in the documentation...
109  *
110  * FUNCTIONS: The CLOCKs structure defines possible functions to
111  *          handle various clock functions.
112  *
113  *          The standard POSIX timer management code assumes the
114  *          following: 1.) The k_itimer struct (sched.h) is used for
115  *          the timer.  2.) The list, it_lock, it_clock, it_id and
116  *          it_pid fields are not modified by timer code.
117  *
118  * Permissions: It is assumed that the clock_settime() function defined
119  *          for each clock will take care of permission checks.  Some
120  *          clocks may be set able by any user (i.e. local process
121  *          clocks) others not.  Currently the only set able clock we
122  *          have is CLOCK_REALTIME and its high res counter part, both of
123  *          which we beg off on and pass to do_sys_settimeofday().
124  */
125 static struct k_itimer *__lock_timer(timer_t timer_id, unsigned long *flags);
126
127 #define lock_timer(tid, flags)                                             \
128 ({      struct k_itimer *__timr;                                           \
129         __cond_lock(&__timr->it_lock, __timr = __lock_timer(tid, flags));  \
130         __timr;                                                            \
131 })
132
133 static int hash(struct signal_struct *sig, unsigned int nr)
134 {
135         return hash_32(hash32_ptr(sig) ^ nr, HASH_BITS(posix_timers_hashtable));
136 }
137
138 static struct k_itimer *__posix_timers_find(struct hlist_head *head,
139                                             struct signal_struct *sig,
140                                             timer_t id)
141 {
142         struct k_itimer *timer;
143
144         hlist_for_each_entry_rcu(timer, head, t_hash) {
145                 if ((timer->it_signal == sig) && (timer->it_id == id))
146                         return timer;
147         }
148         return NULL;
149 }
150
151 static struct k_itimer *posix_timer_by_id(timer_t id)
152 {
153         struct signal_struct *sig = current->signal;
154         struct hlist_head *head = &posix_timers_hashtable[hash(sig, id)];
155
156         return __posix_timers_find(head, sig, id);
157 }
158
159 static int posix_timer_add(struct k_itimer *timer)
160 {
161         struct signal_struct *sig = current->signal;
162         int first_free_id = sig->posix_timer_id;
163         struct hlist_head *head;
164         int ret = -ENOENT;
165
166         do {
167                 spin_lock(&hash_lock);
168                 head = &posix_timers_hashtable[hash(sig, sig->posix_timer_id)];
169                 if (!__posix_timers_find(head, sig, sig->posix_timer_id)) {
170                         hlist_add_head_rcu(&timer->t_hash, head);
171                         ret = sig->posix_timer_id;
172                 }
173                 if (++sig->posix_timer_id < 0)
174                         sig->posix_timer_id = 0;
175                 if ((sig->posix_timer_id == first_free_id) && (ret == -ENOENT))
176                         /* Loop over all possible ids completed */
177                         ret = -EAGAIN;
178                 spin_unlock(&hash_lock);
179         } while (ret == -ENOENT);
180         return ret;
181 }
182
183 static inline void unlock_timer(struct k_itimer *timr, unsigned long flags)
184 {
185         spin_unlock_irqrestore(&timr->it_lock, flags);
186 }
187
188 /* Get clock_realtime */
189 static int posix_clock_realtime_get(clockid_t which_clock, struct timespec64 *tp)
190 {
191         ktime_get_real_ts64(tp);
192         return 0;
193 }
194
195 /* Set clock_realtime */
196 static int posix_clock_realtime_set(const clockid_t which_clock,
197                                     const struct timespec64 *tp)
198 {
199         return do_sys_settimeofday64(tp, NULL);
200 }
201
202 static int posix_clock_realtime_adj(const clockid_t which_clock,
203                                     struct timex *t)
204 {
205         return do_adjtimex(t);
206 }
207
208 /*
209  * Get monotonic time for posix timers
210  */
211 static int posix_ktime_get_ts(clockid_t which_clock, struct timespec64 *tp)
212 {
213         ktime_get_ts64(tp);
214         return 0;
215 }
216
217 /*
218  * Get monotonic-raw time for posix timers
219  */
220 static int posix_get_monotonic_raw(clockid_t which_clock, struct timespec64 *tp)
221 {
222         ktime_get_raw_ts64(tp);
223         return 0;
224 }
225
226
227 static int posix_get_realtime_coarse(clockid_t which_clock, struct timespec64 *tp)
228 {
229         ktime_get_coarse_real_ts64(tp);
230         return 0;
231 }
232
233 static int posix_get_monotonic_coarse(clockid_t which_clock,
234                                                 struct timespec64 *tp)
235 {
236         ktime_get_coarse_ts64(tp);
237         return 0;
238 }
239
240 static int posix_get_coarse_res(const clockid_t which_clock, struct timespec64 *tp)
241 {
242         *tp = ktime_to_timespec64(KTIME_LOW_RES);
243         return 0;
244 }
245
246 static int posix_get_boottime(const clockid_t which_clock, struct timespec64 *tp)
247 {
248         ktime_get_boottime_ts64(tp);
249         return 0;
250 }
251
252 static int posix_get_tai(clockid_t which_clock, struct timespec64 *tp)
253 {
254         ktime_get_clocktai_ts64(tp);
255         return 0;
256 }
257
258 static int posix_get_hrtimer_res(clockid_t which_clock, struct timespec64 *tp)
259 {
260         tp->tv_sec = 0;
261         tp->tv_nsec = hrtimer_resolution;
262         return 0;
263 }
264
265 /*
266  * Initialize everything, well, just everything in Posix clocks/timers ;)
267  */
268 static __init int init_posix_timers(void)
269 {
270         posix_timers_cache = kmem_cache_create("posix_timers_cache",
271                                         sizeof (struct k_itimer), 0, SLAB_PANIC,
272                                         NULL);
273         return 0;
274 }
275 __initcall(init_posix_timers);
276
277 /*
278  * The siginfo si_overrun field and the return value of timer_getoverrun(2)
279  * are of type int. Clamp the overrun value to INT_MAX
280  */
281 static inline int timer_overrun_to_int(struct k_itimer *timr, int baseval)
282 {
283         s64 sum = timr->it_overrun_last + (s64)baseval;
284
285         return sum > (s64)INT_MAX ? INT_MAX : (int)sum;
286 }
287
288 static void common_hrtimer_rearm(struct k_itimer *timr)
289 {
290         struct hrtimer *timer = &timr->it.real.timer;
291
292         if (!timr->it_interval)
293                 return;
294
295         timr->it_overrun += hrtimer_forward(timer, timer->base->get_time(),
296                                             timr->it_interval);
297         hrtimer_restart(timer);
298 }
299
300 /*
301  * This function is exported for use by the signal deliver code.  It is
302  * called just prior to the info block being released and passes that
303  * block to us.  It's function is to update the overrun entry AND to
304  * restart the timer.  It should only be called if the timer is to be
305  * restarted (i.e. we have flagged this in the sys_private entry of the
306  * info block).
307  *
308  * To protect against the timer going away while the interrupt is queued,
309  * we require that the it_requeue_pending flag be set.
310  */
311 void posixtimer_rearm(struct kernel_siginfo *info)
312 {
313         struct k_itimer *timr;
314         unsigned long flags;
315
316         timr = lock_timer(info->si_tid, &flags);
317         if (!timr)
318                 return;
319
320         if (timr->it_requeue_pending == info->si_sys_private) {
321                 timr->kclock->timer_rearm(timr);
322
323                 timr->it_active = 1;
324                 timr->it_overrun_last = timr->it_overrun;
325                 timr->it_overrun = -1LL;
326                 ++timr->it_requeue_pending;
327
328                 info->si_overrun = timer_overrun_to_int(timr, info->si_overrun);
329         }
330
331         unlock_timer(timr, flags);
332 }
333
334 int posix_timer_event(struct k_itimer *timr, int si_private)
335 {
336         enum pid_type type;
337         int ret = -1;
338         /*
339          * FIXME: if ->sigq is queued we can race with
340          * dequeue_signal()->posixtimer_rearm().
341          *
342          * If dequeue_signal() sees the "right" value of
343          * si_sys_private it calls posixtimer_rearm().
344          * We re-queue ->sigq and drop ->it_lock().
345          * posixtimer_rearm() locks the timer
346          * and re-schedules it while ->sigq is pending.
347          * Not really bad, but not that we want.
348          */
349         timr->sigq->info.si_sys_private = si_private;
350
351         type = !(timr->it_sigev_notify & SIGEV_THREAD_ID) ? PIDTYPE_TGID : PIDTYPE_PID;
352         ret = send_sigqueue(timr->sigq, timr->it_pid, type);
353         /* If we failed to send the signal the timer stops. */
354         return ret > 0;
355 }
356
357 /*
358  * This function gets called when a POSIX.1b interval timer expires.  It
359  * is used as a callback from the kernel internal timer.  The
360  * run_timer_list code ALWAYS calls with interrupts on.
361
362  * This code is for CLOCK_REALTIME* and CLOCK_MONOTONIC* timers.
363  */
364 static enum hrtimer_restart posix_timer_fn(struct hrtimer *timer)
365 {
366         struct k_itimer *timr;
367         unsigned long flags;
368         int si_private = 0;
369         enum hrtimer_restart ret = HRTIMER_NORESTART;
370
371         timr = container_of(timer, struct k_itimer, it.real.timer);
372         spin_lock_irqsave(&timr->it_lock, flags);
373
374         timr->it_active = 0;
375         if (timr->it_interval != 0)
376                 si_private = ++timr->it_requeue_pending;
377
378         if (posix_timer_event(timr, si_private)) {
379                 /*
380                  * signal was not sent because of sig_ignor
381                  * we will not get a call back to restart it AND
382                  * it should be restarted.
383                  */
384                 if (timr->it_interval != 0) {
385                         ktime_t now = hrtimer_cb_get_time(timer);
386
387                         /*
388                          * FIXME: What we really want, is to stop this
389                          * timer completely and restart it in case the
390                          * SIG_IGN is removed. This is a non trivial
391                          * change which involves sighand locking
392                          * (sigh !), which we don't want to do late in
393                          * the release cycle.
394                          *
395                          * For now we just let timers with an interval
396                          * less than a jiffie expire every jiffie to
397                          * avoid softirq starvation in case of SIG_IGN
398                          * and a very small interval, which would put
399                          * the timer right back on the softirq pending
400                          * list. By moving now ahead of time we trick
401                          * hrtimer_forward() to expire the timer
402                          * later, while we still maintain the overrun
403                          * accuracy, but have some inconsistency in
404                          * the timer_gettime() case. This is at least
405                          * better than a starved softirq. A more
406                          * complex fix which solves also another related
407                          * inconsistency is already in the pipeline.
408                          */
409 #ifdef CONFIG_HIGH_RES_TIMERS
410                         {
411                                 ktime_t kj = NSEC_PER_SEC / HZ;
412
413                                 if (timr->it_interval < kj)
414                                         now = ktime_add(now, kj);
415                         }
416 #endif
417                         timr->it_overrun += hrtimer_forward(timer, now,
418                                                             timr->it_interval);
419                         ret = HRTIMER_RESTART;
420                         ++timr->it_requeue_pending;
421                         timr->it_active = 1;
422                 }
423         }
424
425         unlock_timer(timr, flags);
426         return ret;
427 }
428
429 static struct pid *good_sigevent(sigevent_t * event)
430 {
431         struct pid *pid = task_tgid(current);
432         struct task_struct *rtn;
433
434         switch (event->sigev_notify) {
435         case SIGEV_SIGNAL | SIGEV_THREAD_ID:
436                 pid = find_vpid(event->sigev_notify_thread_id);
437                 rtn = pid_task(pid, PIDTYPE_PID);
438                 if (!rtn || !same_thread_group(rtn, current))
439                         return NULL;
440                 /* FALLTHRU */
441         case SIGEV_SIGNAL:
442         case SIGEV_THREAD:
443                 if (event->sigev_signo <= 0 || event->sigev_signo > SIGRTMAX)
444                         return NULL;
445                 /* FALLTHRU */
446         case SIGEV_NONE:
447                 return pid;
448         default:
449                 return NULL;
450         }
451 }
452
453 static struct k_itimer * alloc_posix_timer(void)
454 {
455         struct k_itimer *tmr;
456         tmr = kmem_cache_zalloc(posix_timers_cache, GFP_KERNEL);
457         if (!tmr)
458                 return tmr;
459         if (unlikely(!(tmr->sigq = sigqueue_alloc()))) {
460                 kmem_cache_free(posix_timers_cache, tmr);
461                 return NULL;
462         }
463         clear_siginfo(&tmr->sigq->info);
464         return tmr;
465 }
466
467 static void k_itimer_rcu_free(struct rcu_head *head)
468 {
469         struct k_itimer *tmr = container_of(head, struct k_itimer, it.rcu);
470
471         kmem_cache_free(posix_timers_cache, tmr);
472 }
473
474 #define IT_ID_SET       1
475 #define IT_ID_NOT_SET   0
476 static void release_posix_timer(struct k_itimer *tmr, int it_id_set)
477 {
478         if (it_id_set) {
479                 unsigned long flags;
480                 spin_lock_irqsave(&hash_lock, flags);
481                 hlist_del_rcu(&tmr->t_hash);
482                 spin_unlock_irqrestore(&hash_lock, flags);
483         }
484         put_pid(tmr->it_pid);
485         sigqueue_free(tmr->sigq);
486         call_rcu(&tmr->it.rcu, k_itimer_rcu_free);
487 }
488
489 static int common_timer_create(struct k_itimer *new_timer)
490 {
491         hrtimer_init(&new_timer->it.real.timer, new_timer->it_clock, 0);
492         return 0;
493 }
494
495 /* Create a POSIX.1b interval timer. */
496 static int do_timer_create(clockid_t which_clock, struct sigevent *event,
497                            timer_t __user *created_timer_id)
498 {
499         const struct k_clock *kc = clockid_to_kclock(which_clock);
500         struct k_itimer *new_timer;
501         int error, new_timer_id;
502         int it_id_set = IT_ID_NOT_SET;
503
504         if (!kc)
505                 return -EINVAL;
506         if (!kc->timer_create)
507                 return -EOPNOTSUPP;
508
509         new_timer = alloc_posix_timer();
510         if (unlikely(!new_timer))
511                 return -EAGAIN;
512
513         spin_lock_init(&new_timer->it_lock);
514         new_timer_id = posix_timer_add(new_timer);
515         if (new_timer_id < 0) {
516                 error = new_timer_id;
517                 goto out;
518         }
519
520         it_id_set = IT_ID_SET;
521         new_timer->it_id = (timer_t) new_timer_id;
522         new_timer->it_clock = which_clock;
523         new_timer->kclock = kc;
524         new_timer->it_overrun = -1LL;
525
526         if (event) {
527                 rcu_read_lock();
528                 new_timer->it_pid = get_pid(good_sigevent(event));
529                 rcu_read_unlock();
530                 if (!new_timer->it_pid) {
531                         error = -EINVAL;
532                         goto out;
533                 }
534                 new_timer->it_sigev_notify     = event->sigev_notify;
535                 new_timer->sigq->info.si_signo = event->sigev_signo;
536                 new_timer->sigq->info.si_value = event->sigev_value;
537         } else {
538                 new_timer->it_sigev_notify     = SIGEV_SIGNAL;
539                 new_timer->sigq->info.si_signo = SIGALRM;
540                 memset(&new_timer->sigq->info.si_value, 0, sizeof(sigval_t));
541                 new_timer->sigq->info.si_value.sival_int = new_timer->it_id;
542                 new_timer->it_pid = get_pid(task_tgid(current));
543         }
544
545         new_timer->sigq->info.si_tid   = new_timer->it_id;
546         new_timer->sigq->info.si_code  = SI_TIMER;
547
548         if (copy_to_user(created_timer_id,
549                          &new_timer_id, sizeof (new_timer_id))) {
550                 error = -EFAULT;
551                 goto out;
552         }
553
554         error = kc->timer_create(new_timer);
555         if (error)
556                 goto out;
557
558         spin_lock_irq(&current->sighand->siglock);
559         new_timer->it_signal = current->signal;
560         list_add(&new_timer->list, &current->signal->posix_timers);
561         spin_unlock_irq(&current->sighand->siglock);
562
563         return 0;
564         /*
565          * In the case of the timer belonging to another task, after
566          * the task is unlocked, the timer is owned by the other task
567          * and may cease to exist at any time.  Don't use or modify
568          * new_timer after the unlock call.
569          */
570 out:
571         release_posix_timer(new_timer, it_id_set);
572         return error;
573 }
574
575 SYSCALL_DEFINE3(timer_create, const clockid_t, which_clock,
576                 struct sigevent __user *, timer_event_spec,
577                 timer_t __user *, created_timer_id)
578 {
579         if (timer_event_spec) {
580                 sigevent_t event;
581
582                 if (copy_from_user(&event, timer_event_spec, sizeof (event)))
583                         return -EFAULT;
584                 return do_timer_create(which_clock, &event, created_timer_id);
585         }
586         return do_timer_create(which_clock, NULL, created_timer_id);
587 }
588
589 #ifdef CONFIG_COMPAT
590 COMPAT_SYSCALL_DEFINE3(timer_create, clockid_t, which_clock,
591                        struct compat_sigevent __user *, timer_event_spec,
592                        timer_t __user *, created_timer_id)
593 {
594         if (timer_event_spec) {
595                 sigevent_t event;
596
597                 if (get_compat_sigevent(&event, timer_event_spec))
598                         return -EFAULT;
599                 return do_timer_create(which_clock, &event, created_timer_id);
600         }
601         return do_timer_create(which_clock, NULL, created_timer_id);
602 }
603 #endif
604
605 /*
606  * Locking issues: We need to protect the result of the id look up until
607  * we get the timer locked down so it is not deleted under us.  The
608  * removal is done under the idr spinlock so we use that here to bridge
609  * the find to the timer lock.  To avoid a dead lock, the timer id MUST
610  * be release with out holding the timer lock.
611  */
612 static struct k_itimer *__lock_timer(timer_t timer_id, unsigned long *flags)
613 {
614         struct k_itimer *timr;
615
616         /*
617          * timer_t could be any type >= int and we want to make sure any
618          * @timer_id outside positive int range fails lookup.
619          */
620         if ((unsigned long long)timer_id > INT_MAX)
621                 return NULL;
622
623         rcu_read_lock();
624         timr = posix_timer_by_id(timer_id);
625         if (timr) {
626                 spin_lock_irqsave(&timr->it_lock, *flags);
627                 if (timr->it_signal == current->signal) {
628                         rcu_read_unlock();
629                         return timr;
630                 }
631                 spin_unlock_irqrestore(&timr->it_lock, *flags);
632         }
633         rcu_read_unlock();
634
635         return NULL;
636 }
637
638 static ktime_t common_hrtimer_remaining(struct k_itimer *timr, ktime_t now)
639 {
640         struct hrtimer *timer = &timr->it.real.timer;
641
642         return __hrtimer_expires_remaining_adjusted(timer, now);
643 }
644
645 static s64 common_hrtimer_forward(struct k_itimer *timr, ktime_t now)
646 {
647         struct hrtimer *timer = &timr->it.real.timer;
648
649         return hrtimer_forward(timer, now, timr->it_interval);
650 }
651
652 /*
653  * Get the time remaining on a POSIX.1b interval timer.  This function
654  * is ALWAYS called with spin_lock_irq on the timer, thus it must not
655  * mess with irq.
656  *
657  * We have a couple of messes to clean up here.  First there is the case
658  * of a timer that has a requeue pending.  These timers should appear to
659  * be in the timer list with an expiry as if we were to requeue them
660  * now.
661  *
662  * The second issue is the SIGEV_NONE timer which may be active but is
663  * not really ever put in the timer list (to save system resources).
664  * This timer may be expired, and if so, we will do it here.  Otherwise
665  * it is the same as a requeue pending timer WRT to what we should
666  * report.
667  */
668 void common_timer_get(struct k_itimer *timr, struct itimerspec64 *cur_setting)
669 {
670         const struct k_clock *kc = timr->kclock;
671         ktime_t now, remaining, iv;
672         struct timespec64 ts64;
673         bool sig_none;
674
675         sig_none = timr->it_sigev_notify == SIGEV_NONE;
676         iv = timr->it_interval;
677
678         /* interval timer ? */
679         if (iv) {
680                 cur_setting->it_interval = ktime_to_timespec64(iv);
681         } else if (!timr->it_active) {
682                 /*
683                  * SIGEV_NONE oneshot timers are never queued. Check them
684                  * below.
685                  */
686                 if (!sig_none)
687                         return;
688         }
689
690         /*
691          * The timespec64 based conversion is suboptimal, but it's not
692          * worth to implement yet another callback.
693          */
694         kc->clock_get(timr->it_clock, &ts64);
695         now = timespec64_to_ktime(ts64);
696
697         /*
698          * When a requeue is pending or this is a SIGEV_NONE timer move the
699          * expiry time forward by intervals, so expiry is > now.
700          */
701         if (iv && (timr->it_requeue_pending & REQUEUE_PENDING || sig_none))
702                 timr->it_overrun += kc->timer_forward(timr, now);
703
704         remaining = kc->timer_remaining(timr, now);
705         /* Return 0 only, when the timer is expired and not pending */
706         if (remaining <= 0) {
707                 /*
708                  * A single shot SIGEV_NONE timer must return 0, when
709                  * it is expired !
710                  */
711                 if (!sig_none)
712                         cur_setting->it_value.tv_nsec = 1;
713         } else {
714                 cur_setting->it_value = ktime_to_timespec64(remaining);
715         }
716 }
717
718 /* Get the time remaining on a POSIX.1b interval timer. */
719 static int do_timer_gettime(timer_t timer_id,  struct itimerspec64 *setting)
720 {
721         struct k_itimer *timr;
722         const struct k_clock *kc;
723         unsigned long flags;
724         int ret = 0;
725
726         timr = lock_timer(timer_id, &flags);
727         if (!timr)
728                 return -EINVAL;
729
730         memset(setting, 0, sizeof(*setting));
731         kc = timr->kclock;
732         if (WARN_ON_ONCE(!kc || !kc->timer_get))
733                 ret = -EINVAL;
734         else
735                 kc->timer_get(timr, setting);
736
737         unlock_timer(timr, flags);
738         return ret;
739 }
740
741 /* Get the time remaining on a POSIX.1b interval timer. */
742 SYSCALL_DEFINE2(timer_gettime, timer_t, timer_id,
743                 struct __kernel_itimerspec __user *, setting)
744 {
745         struct itimerspec64 cur_setting;
746
747         int ret = do_timer_gettime(timer_id, &cur_setting);
748         if (!ret) {
749                 if (put_itimerspec64(&cur_setting, setting))
750                         ret = -EFAULT;
751         }
752         return ret;
753 }
754
755 #ifdef CONFIG_COMPAT_32BIT_TIME
756
757 COMPAT_SYSCALL_DEFINE2(timer_gettime, timer_t, timer_id,
758                        struct old_itimerspec32 __user *, setting)
759 {
760         struct itimerspec64 cur_setting;
761
762         int ret = do_timer_gettime(timer_id, &cur_setting);
763         if (!ret) {
764                 if (put_old_itimerspec32(&cur_setting, setting))
765                         ret = -EFAULT;
766         }
767         return ret;
768 }
769
770 #endif
771
772 /*
773  * Get the number of overruns of a POSIX.1b interval timer.  This is to
774  * be the overrun of the timer last delivered.  At the same time we are
775  * accumulating overruns on the next timer.  The overrun is frozen when
776  * the signal is delivered, either at the notify time (if the info block
777  * is not queued) or at the actual delivery time (as we are informed by
778  * the call back to posixtimer_rearm().  So all we need to do is
779  * to pick up the frozen overrun.
780  */
781 SYSCALL_DEFINE1(timer_getoverrun, timer_t, timer_id)
782 {
783         struct k_itimer *timr;
784         int overrun;
785         unsigned long flags;
786
787         timr = lock_timer(timer_id, &flags);
788         if (!timr)
789                 return -EINVAL;
790
791         overrun = timer_overrun_to_int(timr, 0);
792         unlock_timer(timr, flags);
793
794         return overrun;
795 }
796
797 static void common_hrtimer_arm(struct k_itimer *timr, ktime_t expires,
798                                bool absolute, bool sigev_none)
799 {
800         struct hrtimer *timer = &timr->it.real.timer;
801         enum hrtimer_mode mode;
802
803         mode = absolute ? HRTIMER_MODE_ABS : HRTIMER_MODE_REL;
804         /*
805          * Posix magic: Relative CLOCK_REALTIME timers are not affected by
806          * clock modifications, so they become CLOCK_MONOTONIC based under the
807          * hood. See hrtimer_init(). Update timr->kclock, so the generic
808          * functions which use timr->kclock->clock_get() work.
809          *
810          * Note: it_clock stays unmodified, because the next timer_set() might
811          * use ABSTIME, so it needs to switch back.
812          */
813         if (timr->it_clock == CLOCK_REALTIME)
814                 timr->kclock = absolute ? &clock_realtime : &clock_monotonic;
815
816         hrtimer_init(&timr->it.real.timer, timr->it_clock, mode);
817         timr->it.real.timer.function = posix_timer_fn;
818
819         if (!absolute)
820                 expires = ktime_add_safe(expires, timer->base->get_time());
821         hrtimer_set_expires(timer, expires);
822
823         if (!sigev_none)
824                 hrtimer_start_expires(timer, HRTIMER_MODE_ABS);
825 }
826
827 static int common_hrtimer_try_to_cancel(struct k_itimer *timr)
828 {
829         return hrtimer_try_to_cancel(&timr->it.real.timer);
830 }
831
832 /* Set a POSIX.1b interval timer. */
833 int common_timer_set(struct k_itimer *timr, int flags,
834                      struct itimerspec64 *new_setting,
835                      struct itimerspec64 *old_setting)
836 {
837         const struct k_clock *kc = timr->kclock;
838         bool sigev_none;
839         ktime_t expires;
840
841         if (old_setting)
842                 common_timer_get(timr, old_setting);
843
844         /* Prevent rearming by clearing the interval */
845         timr->it_interval = 0;
846         /*
847          * Careful here. On SMP systems the timer expiry function could be
848          * active and spinning on timr->it_lock.
849          */
850         if (kc->timer_try_to_cancel(timr) < 0)
851                 return TIMER_RETRY;
852
853         timr->it_active = 0;
854         timr->it_requeue_pending = (timr->it_requeue_pending + 2) &
855                 ~REQUEUE_PENDING;
856         timr->it_overrun_last = 0;
857
858         /* Switch off the timer when it_value is zero */
859         if (!new_setting->it_value.tv_sec && !new_setting->it_value.tv_nsec)
860                 return 0;
861
862         timr->it_interval = timespec64_to_ktime(new_setting->it_interval);
863         expires = timespec64_to_ktime(new_setting->it_value);
864         sigev_none = timr->it_sigev_notify == SIGEV_NONE;
865
866         kc->timer_arm(timr, expires, flags & TIMER_ABSTIME, sigev_none);
867         timr->it_active = !sigev_none;
868         return 0;
869 }
870
871 static int do_timer_settime(timer_t timer_id, int flags,
872                             struct itimerspec64 *new_spec64,
873                             struct itimerspec64 *old_spec64)
874 {
875         const struct k_clock *kc;
876         struct k_itimer *timr;
877         unsigned long flag;
878         int error = 0;
879
880         if (!timespec64_valid(&new_spec64->it_interval) ||
881             !timespec64_valid(&new_spec64->it_value))
882                 return -EINVAL;
883
884         if (old_spec64)
885                 memset(old_spec64, 0, sizeof(*old_spec64));
886 retry:
887         timr = lock_timer(timer_id, &flag);
888         if (!timr)
889                 return -EINVAL;
890
891         kc = timr->kclock;
892         if (WARN_ON_ONCE(!kc || !kc->timer_set))
893                 error = -EINVAL;
894         else
895                 error = kc->timer_set(timr, flags, new_spec64, old_spec64);
896
897         unlock_timer(timr, flag);
898         if (error == TIMER_RETRY) {
899                 old_spec64 = NULL;      // We already got the old time...
900                 goto retry;
901         }
902
903         return error;
904 }
905
906 /* Set a POSIX.1b interval timer */
907 SYSCALL_DEFINE4(timer_settime, timer_t, timer_id, int, flags,
908                 const struct __kernel_itimerspec __user *, new_setting,
909                 struct __kernel_itimerspec __user *, old_setting)
910 {
911         struct itimerspec64 new_spec, old_spec;
912         struct itimerspec64 *rtn = old_setting ? &old_spec : NULL;
913         int error = 0;
914
915         if (!new_setting)
916                 return -EINVAL;
917
918         if (get_itimerspec64(&new_spec, new_setting))
919                 return -EFAULT;
920
921         error = do_timer_settime(timer_id, flags, &new_spec, rtn);
922         if (!error && old_setting) {
923                 if (put_itimerspec64(&old_spec, old_setting))
924                         error = -EFAULT;
925         }
926         return error;
927 }
928
929 #ifdef CONFIG_COMPAT_32BIT_TIME
930 COMPAT_SYSCALL_DEFINE4(timer_settime, timer_t, timer_id, int, flags,
931                        struct old_itimerspec32 __user *, new,
932                        struct old_itimerspec32 __user *, old)
933 {
934         struct itimerspec64 new_spec, old_spec;
935         struct itimerspec64 *rtn = old ? &old_spec : NULL;
936         int error = 0;
937
938         if (!new)
939                 return -EINVAL;
940         if (get_old_itimerspec32(&new_spec, new))
941                 return -EFAULT;
942
943         error = do_timer_settime(timer_id, flags, &new_spec, rtn);
944         if (!error && old) {
945                 if (put_old_itimerspec32(&old_spec, old))
946                         error = -EFAULT;
947         }
948         return error;
949 }
950 #endif
951
952 int common_timer_del(struct k_itimer *timer)
953 {
954         const struct k_clock *kc = timer->kclock;
955
956         timer->it_interval = 0;
957         if (kc->timer_try_to_cancel(timer) < 0)
958                 return TIMER_RETRY;
959         timer->it_active = 0;
960         return 0;
961 }
962
963 static inline int timer_delete_hook(struct k_itimer *timer)
964 {
965         const struct k_clock *kc = timer->kclock;
966
967         if (WARN_ON_ONCE(!kc || !kc->timer_del))
968                 return -EINVAL;
969         return kc->timer_del(timer);
970 }
971
972 /* Delete a POSIX.1b interval timer. */
973 SYSCALL_DEFINE1(timer_delete, timer_t, timer_id)
974 {
975         struct k_itimer *timer;
976         unsigned long flags;
977
978 retry_delete:
979         timer = lock_timer(timer_id, &flags);
980         if (!timer)
981                 return -EINVAL;
982
983         if (timer_delete_hook(timer) == TIMER_RETRY) {
984                 unlock_timer(timer, flags);
985                 goto retry_delete;
986         }
987
988         spin_lock(&current->sighand->siglock);
989         list_del(&timer->list);
990         spin_unlock(&current->sighand->siglock);
991         /*
992          * This keeps any tasks waiting on the spin lock from thinking
993          * they got something (see the lock code above).
994          */
995         timer->it_signal = NULL;
996
997         unlock_timer(timer, flags);
998         release_posix_timer(timer, IT_ID_SET);
999         return 0;
1000 }
1001
1002 /*
1003  * return timer owned by the process, used by exit_itimers
1004  */
1005 static void itimer_delete(struct k_itimer *timer)
1006 {
1007         unsigned long flags;
1008
1009 retry_delete:
1010         spin_lock_irqsave(&timer->it_lock, flags);
1011
1012         if (timer_delete_hook(timer) == TIMER_RETRY) {
1013                 unlock_timer(timer, flags);
1014                 goto retry_delete;
1015         }
1016         list_del(&timer->list);
1017         /*
1018          * This keeps any tasks waiting on the spin lock from thinking
1019          * they got something (see the lock code above).
1020          */
1021         timer->it_signal = NULL;
1022
1023         unlock_timer(timer, flags);
1024         release_posix_timer(timer, IT_ID_SET);
1025 }
1026
1027 /*
1028  * This is called by do_exit or de_thread, only when there are no more
1029  * references to the shared signal_struct.
1030  */
1031 void exit_itimers(struct signal_struct *sig)
1032 {
1033         struct k_itimer *tmr;
1034
1035         while (!list_empty(&sig->posix_timers)) {
1036                 tmr = list_entry(sig->posix_timers.next, struct k_itimer, list);
1037                 itimer_delete(tmr);
1038         }
1039 }
1040
1041 SYSCALL_DEFINE2(clock_settime, const clockid_t, which_clock,
1042                 const struct __kernel_timespec __user *, tp)
1043 {
1044         const struct k_clock *kc = clockid_to_kclock(which_clock);
1045         struct timespec64 new_tp;
1046
1047         if (!kc || !kc->clock_set)
1048                 return -EINVAL;
1049
1050         if (get_timespec64(&new_tp, tp))
1051                 return -EFAULT;
1052
1053         return kc->clock_set(which_clock, &new_tp);
1054 }
1055
1056 SYSCALL_DEFINE2(clock_gettime, const clockid_t, which_clock,
1057                 struct __kernel_timespec __user *, tp)
1058 {
1059         const struct k_clock *kc = clockid_to_kclock(which_clock);
1060         struct timespec64 kernel_tp;
1061         int error;
1062
1063         if (!kc)
1064                 return -EINVAL;
1065
1066         error = kc->clock_get(which_clock, &kernel_tp);
1067
1068         if (!error && put_timespec64(&kernel_tp, tp))
1069                 error = -EFAULT;
1070
1071         return error;
1072 }
1073
1074 SYSCALL_DEFINE2(clock_adjtime, const clockid_t, which_clock,
1075                 struct timex __user *, utx)
1076 {
1077         const struct k_clock *kc = clockid_to_kclock(which_clock);
1078         struct timex ktx;
1079         int err;
1080
1081         if (!kc)
1082                 return -EINVAL;
1083         if (!kc->clock_adj)
1084                 return -EOPNOTSUPP;
1085
1086         if (copy_from_user(&ktx, utx, sizeof(ktx)))
1087                 return -EFAULT;
1088
1089         err = kc->clock_adj(which_clock, &ktx);
1090
1091         if (err >= 0 && copy_to_user(utx, &ktx, sizeof(ktx)))
1092                 return -EFAULT;
1093
1094         return err;
1095 }
1096
1097 SYSCALL_DEFINE2(clock_getres, const clockid_t, which_clock,
1098                 struct __kernel_timespec __user *, tp)
1099 {
1100         const struct k_clock *kc = clockid_to_kclock(which_clock);
1101         struct timespec64 rtn_tp;
1102         int error;
1103
1104         if (!kc)
1105                 return -EINVAL;
1106
1107         error = kc->clock_getres(which_clock, &rtn_tp);
1108
1109         if (!error && tp && put_timespec64(&rtn_tp, tp))
1110                 error = -EFAULT;
1111
1112         return error;
1113 }
1114
1115 #ifdef CONFIG_COMPAT_32BIT_TIME
1116
1117 COMPAT_SYSCALL_DEFINE2(clock_settime, clockid_t, which_clock,
1118                        struct old_timespec32 __user *, tp)
1119 {
1120         const struct k_clock *kc = clockid_to_kclock(which_clock);
1121         struct timespec64 ts;
1122
1123         if (!kc || !kc->clock_set)
1124                 return -EINVAL;
1125
1126         if (get_old_timespec32(&ts, tp))
1127                 return -EFAULT;
1128
1129         return kc->clock_set(which_clock, &ts);
1130 }
1131
1132 COMPAT_SYSCALL_DEFINE2(clock_gettime, clockid_t, which_clock,
1133                        struct old_timespec32 __user *, tp)
1134 {
1135         const struct k_clock *kc = clockid_to_kclock(which_clock);
1136         struct timespec64 ts;
1137         int err;
1138
1139         if (!kc)
1140                 return -EINVAL;
1141
1142         err = kc->clock_get(which_clock, &ts);
1143
1144         if (!err && put_old_timespec32(&ts, tp))
1145                 err = -EFAULT;
1146
1147         return err;
1148 }
1149
1150 #endif
1151
1152 #ifdef CONFIG_COMPAT
1153
1154 COMPAT_SYSCALL_DEFINE2(clock_adjtime, clockid_t, which_clock,
1155                        struct compat_timex __user *, utp)
1156 {
1157         const struct k_clock *kc = clockid_to_kclock(which_clock);
1158         struct timex ktx;
1159         int err;
1160
1161         if (!kc)
1162                 return -EINVAL;
1163         if (!kc->clock_adj)
1164                 return -EOPNOTSUPP;
1165
1166         err = compat_get_timex(&ktx, utp);
1167         if (err)
1168                 return err;
1169
1170         err = kc->clock_adj(which_clock, &ktx);
1171
1172         if (err >= 0)
1173                 err = compat_put_timex(utp, &ktx);
1174
1175         return err;
1176 }
1177
1178 #endif
1179
1180 #ifdef CONFIG_COMPAT_32BIT_TIME
1181
1182 COMPAT_SYSCALL_DEFINE2(clock_getres, clockid_t, which_clock,
1183                        struct old_timespec32 __user *, tp)
1184 {
1185         const struct k_clock *kc = clockid_to_kclock(which_clock);
1186         struct timespec64 ts;
1187         int err;
1188
1189         if (!kc)
1190                 return -EINVAL;
1191
1192         err = kc->clock_getres(which_clock, &ts);
1193         if (!err && tp && put_old_timespec32(&ts, tp))
1194                 return -EFAULT;
1195
1196         return err;
1197 }
1198
1199 #endif
1200
1201 /*
1202  * nanosleep for monotonic and realtime clocks
1203  */
1204 static int common_nsleep(const clockid_t which_clock, int flags,
1205                          const struct timespec64 *rqtp)
1206 {
1207         return hrtimer_nanosleep(rqtp, flags & TIMER_ABSTIME ?
1208                                  HRTIMER_MODE_ABS : HRTIMER_MODE_REL,
1209                                  which_clock);
1210 }
1211
1212 SYSCALL_DEFINE4(clock_nanosleep, const clockid_t, which_clock, int, flags,
1213                 const struct __kernel_timespec __user *, rqtp,
1214                 struct __kernel_timespec __user *, rmtp)
1215 {
1216         const struct k_clock *kc = clockid_to_kclock(which_clock);
1217         struct timespec64 t;
1218
1219         if (!kc)
1220                 return -EINVAL;
1221         if (!kc->nsleep)
1222                 return -EOPNOTSUPP;
1223
1224         if (get_timespec64(&t, rqtp))
1225                 return -EFAULT;
1226
1227         if (!timespec64_valid(&t))
1228                 return -EINVAL;
1229         if (flags & TIMER_ABSTIME)
1230                 rmtp = NULL;
1231         current->restart_block.nanosleep.type = rmtp ? TT_NATIVE : TT_NONE;
1232         current->restart_block.nanosleep.rmtp = rmtp;
1233
1234         return kc->nsleep(which_clock, flags, &t);
1235 }
1236
1237 #ifdef CONFIG_COMPAT_32BIT_TIME
1238
1239 COMPAT_SYSCALL_DEFINE4(clock_nanosleep, clockid_t, which_clock, int, flags,
1240                        struct old_timespec32 __user *, rqtp,
1241                        struct old_timespec32 __user *, rmtp)
1242 {
1243         const struct k_clock *kc = clockid_to_kclock(which_clock);
1244         struct timespec64 t;
1245
1246         if (!kc)
1247                 return -EINVAL;
1248         if (!kc->nsleep)
1249                 return -EOPNOTSUPP;
1250
1251         if (get_old_timespec32(&t, rqtp))
1252                 return -EFAULT;
1253
1254         if (!timespec64_valid(&t))
1255                 return -EINVAL;
1256         if (flags & TIMER_ABSTIME)
1257                 rmtp = NULL;
1258         current->restart_block.nanosleep.type = rmtp ? TT_COMPAT : TT_NONE;
1259         current->restart_block.nanosleep.compat_rmtp = rmtp;
1260
1261         return kc->nsleep(which_clock, flags, &t);
1262 }
1263
1264 #endif
1265
1266 static const struct k_clock clock_realtime = {
1267         .clock_getres           = posix_get_hrtimer_res,
1268         .clock_get              = posix_clock_realtime_get,
1269         .clock_set              = posix_clock_realtime_set,
1270         .clock_adj              = posix_clock_realtime_adj,
1271         .nsleep                 = common_nsleep,
1272         .timer_create           = common_timer_create,
1273         .timer_set              = common_timer_set,
1274         .timer_get              = common_timer_get,
1275         .timer_del              = common_timer_del,
1276         .timer_rearm            = common_hrtimer_rearm,
1277         .timer_forward          = common_hrtimer_forward,
1278         .timer_remaining        = common_hrtimer_remaining,
1279         .timer_try_to_cancel    = common_hrtimer_try_to_cancel,
1280         .timer_arm              = common_hrtimer_arm,
1281 };
1282
1283 static const struct k_clock clock_monotonic = {
1284         .clock_getres           = posix_get_hrtimer_res,
1285         .clock_get              = posix_ktime_get_ts,
1286         .nsleep                 = common_nsleep,
1287         .timer_create           = common_timer_create,
1288         .timer_set              = common_timer_set,
1289         .timer_get              = common_timer_get,
1290         .timer_del              = common_timer_del,
1291         .timer_rearm            = common_hrtimer_rearm,
1292         .timer_forward          = common_hrtimer_forward,
1293         .timer_remaining        = common_hrtimer_remaining,
1294         .timer_try_to_cancel    = common_hrtimer_try_to_cancel,
1295         .timer_arm              = common_hrtimer_arm,
1296 };
1297
1298 static const struct k_clock clock_monotonic_raw = {
1299         .clock_getres           = posix_get_hrtimer_res,
1300         .clock_get              = posix_get_monotonic_raw,
1301 };
1302
1303 static const struct k_clock clock_realtime_coarse = {
1304         .clock_getres           = posix_get_coarse_res,
1305         .clock_get              = posix_get_realtime_coarse,
1306 };
1307
1308 static const struct k_clock clock_monotonic_coarse = {
1309         .clock_getres           = posix_get_coarse_res,
1310         .clock_get              = posix_get_monotonic_coarse,
1311 };
1312
1313 static const struct k_clock clock_tai = {
1314         .clock_getres           = posix_get_hrtimer_res,
1315         .clock_get              = posix_get_tai,
1316         .nsleep                 = common_nsleep,
1317         .timer_create           = common_timer_create,
1318         .timer_set              = common_timer_set,
1319         .timer_get              = common_timer_get,
1320         .timer_del              = common_timer_del,
1321         .timer_rearm            = common_hrtimer_rearm,
1322         .timer_forward          = common_hrtimer_forward,
1323         .timer_remaining        = common_hrtimer_remaining,
1324         .timer_try_to_cancel    = common_hrtimer_try_to_cancel,
1325         .timer_arm              = common_hrtimer_arm,
1326 };
1327
1328 static const struct k_clock clock_boottime = {
1329         .clock_getres           = posix_get_hrtimer_res,
1330         .clock_get              = posix_get_boottime,
1331         .nsleep                 = common_nsleep,
1332         .timer_create           = common_timer_create,
1333         .timer_set              = common_timer_set,
1334         .timer_get              = common_timer_get,
1335         .timer_del              = common_timer_del,
1336         .timer_rearm            = common_hrtimer_rearm,
1337         .timer_forward          = common_hrtimer_forward,
1338         .timer_remaining        = common_hrtimer_remaining,
1339         .timer_try_to_cancel    = common_hrtimer_try_to_cancel,
1340         .timer_arm              = common_hrtimer_arm,
1341 };
1342
1343 static const struct k_clock * const posix_clocks[] = {
1344         [CLOCK_REALTIME]                = &clock_realtime,
1345         [CLOCK_MONOTONIC]               = &clock_monotonic,
1346         [CLOCK_PROCESS_CPUTIME_ID]      = &clock_process,
1347         [CLOCK_THREAD_CPUTIME_ID]       = &clock_thread,
1348         [CLOCK_MONOTONIC_RAW]           = &clock_monotonic_raw,
1349         [CLOCK_REALTIME_COARSE]         = &clock_realtime_coarse,
1350         [CLOCK_MONOTONIC_COARSE]        = &clock_monotonic_coarse,
1351         [CLOCK_BOOTTIME]                = &clock_boottime,
1352         [CLOCK_REALTIME_ALARM]          = &alarm_clock,
1353         [CLOCK_BOOTTIME_ALARM]          = &alarm_clock,
1354         [CLOCK_TAI]                     = &clock_tai,
1355 };
1356
1357 static const struct k_clock *clockid_to_kclock(const clockid_t id)
1358 {
1359         clockid_t idx = id;
1360
1361         if (id < 0) {
1362                 return (id & CLOCKFD_MASK) == CLOCKFD ?
1363                         &clock_posix_dynamic : &clock_posix_cpu;
1364         }
1365
1366         if (id >= ARRAY_SIZE(posix_clocks))
1367                 return NULL;
1368
1369         return posix_clocks[array_index_nospec(idx, ARRAY_SIZE(posix_clocks))];
1370 }