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