xref: /linux/kernel/time/posix-timers.c (revision 69050f8d6d075dc01af7a5f2f550a8067510366f)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * 2002-10-15  Posix Clocks & timers
4  *                           by George Anzinger george@mvista.com
5  *			     Copyright (C) 2002 2003 by MontaVista Software.
6  *
7  * 2004-06-01  Fix CLOCK_REALTIME clock/timer TIMER_ABSTIME bug.
8  *			     Copyright (C) 2004 Boris Hu
9  *
10  * These are all the functions necessary to implement POSIX clocks & timers
11  */
12 #include <linux/compat.h>
13 #include <linux/compiler.h>
14 #include <linux/init.h>
15 #include <linux/jhash.h>
16 #include <linux/interrupt.h>
17 #include <linux/list.h>
18 #include <linux/memblock.h>
19 #include <linux/nospec.h>
20 #include <linux/posix-clock.h>
21 #include <linux/posix-timers.h>
22 #include <linux/prctl.h>
23 #include <linux/sched/task.h>
24 #include <linux/slab.h>
25 #include <linux/syscalls.h>
26 #include <linux/time.h>
27 #include <linux/time_namespace.h>
28 #include <linux/uaccess.h>
29 
30 #include "timekeeping.h"
31 #include "posix-timers.h"
32 
33 /*
34  * Timers are managed in a hash table for lockless lookup. The hash key is
35  * constructed from current::signal and the timer ID and the timer is
36  * matched against current::signal and the timer ID when walking the hash
37  * bucket list.
38  *
39  * This allows checkpoint/restore to reconstruct the exact timer IDs for
40  * a process.
41  */
42 struct timer_hash_bucket {
43 	spinlock_t		lock;
44 	struct hlist_head	head;
45 };
46 
47 static struct {
48 	struct timer_hash_bucket	*buckets;
49 	unsigned long			mask;
50 	struct kmem_cache		*cache;
51 } __timer_data __ro_after_init __aligned(4*sizeof(long));
52 
53 #define timer_buckets		(__timer_data.buckets)
54 #define timer_hashmask		(__timer_data.mask)
55 #define posix_timers_cache	(__timer_data.cache)
56 
57 static const struct k_clock * const posix_clocks[];
58 static const struct k_clock *clockid_to_kclock(const clockid_t id);
59 static const struct k_clock clock_realtime, clock_monotonic;
60 
61 #define TIMER_ANY_ID		INT_MIN
62 
63 /* SIGEV_THREAD_ID cannot share a bit with the other SIGEV values. */
64 #if SIGEV_THREAD_ID != (SIGEV_THREAD_ID & \
65 			~(SIGEV_SIGNAL | SIGEV_NONE | SIGEV_THREAD))
66 #error "SIGEV_THREAD_ID must not share bit with other SIGEV values!"
67 #endif
68 
69 static struct k_itimer *lock_timer(timer_t timer_id);
70 static inline void unlock_timer(struct k_itimer *timr)
71 {
72 	if (likely((timr)))
73 		spin_unlock_irq(&timr->it_lock);
74 }
75 
76 #define scoped_timer_get_or_fail(_id)					\
77 	scoped_cond_guard(lock_timer, return -EINVAL, _id)
78 
79 #define scoped_timer				(scope)
80 
81 DEFINE_CLASS(lock_timer, struct k_itimer *, unlock_timer(_T), lock_timer(id), timer_t id);
82 DEFINE_CLASS_IS_COND_GUARD(lock_timer);
83 
84 static struct timer_hash_bucket *hash_bucket(struct signal_struct *sig, unsigned int nr)
85 {
86 	return &timer_buckets[jhash2((u32 *)&sig, sizeof(sig) / sizeof(u32), nr) & timer_hashmask];
87 }
88 
89 static struct k_itimer *posix_timer_by_id(timer_t id)
90 {
91 	struct signal_struct *sig = current->signal;
92 	struct timer_hash_bucket *bucket = hash_bucket(sig, id);
93 	struct k_itimer *timer;
94 
95 	hlist_for_each_entry_rcu(timer, &bucket->head, t_hash) {
96 		/* timer->it_signal can be set concurrently */
97 		if ((READ_ONCE(timer->it_signal) == sig) && (timer->it_id == id))
98 			return timer;
99 	}
100 	return NULL;
101 }
102 
103 static inline struct signal_struct *posix_sig_owner(const struct k_itimer *timer)
104 {
105 	unsigned long val = (unsigned long)timer->it_signal;
106 
107 	/*
108 	 * Mask out bit 0, which acts as invalid marker to prevent
109 	 * posix_timer_by_id() detecting it as valid.
110 	 */
111 	return (struct signal_struct *)(val & ~1UL);
112 }
113 
114 static bool posix_timer_hashed(struct timer_hash_bucket *bucket, struct signal_struct *sig,
115 			       timer_t id)
116 {
117 	struct hlist_head *head = &bucket->head;
118 	struct k_itimer *timer;
119 
120 	hlist_for_each_entry_rcu(timer, head, t_hash, lockdep_is_held(&bucket->lock)) {
121 		if ((posix_sig_owner(timer) == sig) && (timer->it_id == id))
122 			return true;
123 	}
124 	return false;
125 }
126 
127 static bool posix_timer_add_at(struct k_itimer *timer, struct signal_struct *sig, unsigned int id)
128 {
129 	struct timer_hash_bucket *bucket = hash_bucket(sig, id);
130 
131 	scoped_guard (spinlock, &bucket->lock) {
132 		/*
133 		 * Validate under the lock as this could have raced against
134 		 * another thread ending up with the same ID, which is
135 		 * highly unlikely, but possible.
136 		 */
137 		if (!posix_timer_hashed(bucket, sig, id)) {
138 			/*
139 			 * Set the timer ID and the signal pointer to make
140 			 * it identifiable in the hash table. The signal
141 			 * pointer has bit 0 set to indicate that it is not
142 			 * yet fully initialized. posix_timer_hashed()
143 			 * masks this bit out, but the syscall lookup fails
144 			 * to match due to it being set. This guarantees
145 			 * that there can't be duplicate timer IDs handed
146 			 * out.
147 			 */
148 			timer->it_id = (timer_t)id;
149 			timer->it_signal = (struct signal_struct *)((unsigned long)sig | 1UL);
150 			hlist_add_head_rcu(&timer->t_hash, &bucket->head);
151 			return true;
152 		}
153 	}
154 	return false;
155 }
156 
157 static int posix_timer_add(struct k_itimer *timer, int req_id)
158 {
159 	struct signal_struct *sig = current->signal;
160 
161 	if (unlikely(req_id != TIMER_ANY_ID)) {
162 		if (!posix_timer_add_at(timer, sig, req_id))
163 			return -EBUSY;
164 
165 		/*
166 		 * Move the ID counter past the requested ID, so that after
167 		 * switching back to normal mode the IDs are outside of the
168 		 * exact allocated region. That avoids ID collisions on the
169 		 * next regular timer_create() invocations.
170 		 */
171 		atomic_set(&sig->next_posix_timer_id, req_id + 1);
172 		return req_id;
173 	}
174 
175 	for (unsigned int cnt = 0; cnt <= INT_MAX; cnt++) {
176 		/* Get the next timer ID and clamp it to positive space */
177 		unsigned int id = atomic_fetch_inc(&sig->next_posix_timer_id) & INT_MAX;
178 
179 		if (posix_timer_add_at(timer, sig, id))
180 			return id;
181 		cond_resched();
182 	}
183 	/* POSIX return code when no timer ID could be allocated */
184 	return -EAGAIN;
185 }
186 
187 static int posix_get_realtime_timespec(clockid_t which_clock, struct timespec64 *tp)
188 {
189 	ktime_get_real_ts64(tp);
190 	return 0;
191 }
192 
193 static ktime_t posix_get_realtime_ktime(clockid_t which_clock)
194 {
195 	return ktime_get_real();
196 }
197 
198 static int posix_clock_realtime_set(const clockid_t which_clock,
199 				    const struct timespec64 *tp)
200 {
201 	return do_sys_settimeofday64(tp, NULL);
202 }
203 
204 static int posix_clock_realtime_adj(const clockid_t which_clock,
205 				    struct __kernel_timex *t)
206 {
207 	return do_adjtimex(t);
208 }
209 
210 static int posix_get_monotonic_timespec(clockid_t which_clock, struct timespec64 *tp)
211 {
212 	ktime_get_ts64(tp);
213 	timens_add_monotonic(tp);
214 	return 0;
215 }
216 
217 static ktime_t posix_get_monotonic_ktime(clockid_t which_clock)
218 {
219 	return ktime_get();
220 }
221 
222 static int posix_get_monotonic_raw(clockid_t which_clock, struct timespec64 *tp)
223 {
224 	ktime_get_raw_ts64(tp);
225 	timens_add_monotonic(tp);
226 	return 0;
227 }
228 
229 static int posix_get_realtime_coarse(clockid_t which_clock, struct timespec64 *tp)
230 {
231 	ktime_get_coarse_real_ts64(tp);
232 	return 0;
233 }
234 
235 static int posix_get_monotonic_coarse(clockid_t which_clock,
236 						struct timespec64 *tp)
237 {
238 	ktime_get_coarse_ts64(tp);
239 	timens_add_monotonic(tp);
240 	return 0;
241 }
242 
243 static int posix_get_coarse_res(const clockid_t which_clock, struct timespec64 *tp)
244 {
245 	*tp = ktime_to_timespec64(KTIME_LOW_RES);
246 	return 0;
247 }
248 
249 static int posix_get_boottime_timespec(const clockid_t which_clock, struct timespec64 *tp)
250 {
251 	ktime_get_boottime_ts64(tp);
252 	timens_add_boottime(tp);
253 	return 0;
254 }
255 
256 static ktime_t posix_get_boottime_ktime(const clockid_t which_clock)
257 {
258 	return ktime_get_boottime();
259 }
260 
261 static int posix_get_tai_timespec(clockid_t which_clock, struct timespec64 *tp)
262 {
263 	ktime_get_clocktai_ts64(tp);
264 	return 0;
265 }
266 
267 static ktime_t posix_get_tai_ktime(clockid_t which_clock)
268 {
269 	return ktime_get_clocktai();
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  * The siginfo si_overrun field and the return value of timer_getoverrun(2)
281  * are of type int. Clamp the overrun value to INT_MAX
282  */
283 static inline int timer_overrun_to_int(struct k_itimer *timr)
284 {
285 	if (timr->it_overrun_last > (s64)INT_MAX)
286 		return INT_MAX;
287 
288 	return (int)timr->it_overrun_last;
289 }
290 
291 static void common_hrtimer_rearm(struct k_itimer *timr)
292 {
293 	struct hrtimer *timer = &timr->it.real.timer;
294 
295 	timr->it_overrun += hrtimer_forward_now(timer, timr->it_interval);
296 	hrtimer_restart(timer);
297 }
298 
299 static bool __posixtimer_deliver_signal(struct kernel_siginfo *info, struct k_itimer *timr)
300 {
301 	guard(spinlock)(&timr->it_lock);
302 
303 	/*
304 	 * Check if the timer is still alive or whether it got modified
305 	 * since the signal was queued. In either case, don't rearm and
306 	 * drop the signal.
307 	 */
308 	if (timr->it_signal_seq != timr->it_sigqueue_seq || WARN_ON_ONCE(!posixtimer_valid(timr)))
309 		return false;
310 
311 	if (!timr->it_interval || WARN_ON_ONCE(timr->it_status != POSIX_TIMER_REQUEUE_PENDING))
312 		return true;
313 
314 	timr->kclock->timer_rearm(timr);
315 	timr->it_status = POSIX_TIMER_ARMED;
316 	timr->it_overrun_last = timr->it_overrun;
317 	timr->it_overrun = -1LL;
318 	++timr->it_signal_seq;
319 	info->si_overrun = timer_overrun_to_int(timr);
320 	return true;
321 }
322 
323 /*
324  * This function is called from the signal delivery code. It decides
325  * whether the signal should be dropped and rearms interval timers.  The
326  * timer can be unconditionally accessed as there is a reference held on
327  * it.
328  */
329 bool posixtimer_deliver_signal(struct kernel_siginfo *info, struct sigqueue *timer_sigq)
330 {
331 	struct k_itimer *timr = container_of(timer_sigq, struct k_itimer, sigq);
332 	bool ret;
333 
334 	/*
335 	 * Release siglock to ensure proper locking order versus
336 	 * timr::it_lock. Keep interrupts disabled.
337 	 */
338 	spin_unlock(&current->sighand->siglock);
339 
340 	ret = __posixtimer_deliver_signal(info, timr);
341 
342 	/* Drop the reference which was acquired when the signal was queued */
343 	posixtimer_putref(timr);
344 
345 	spin_lock(&current->sighand->siglock);
346 	return ret;
347 }
348 
349 void posix_timer_queue_signal(struct k_itimer *timr)
350 {
351 	lockdep_assert_held(&timr->it_lock);
352 
353 	if (!posixtimer_valid(timr))
354 		return;
355 
356 	timr->it_status = timr->it_interval ? POSIX_TIMER_REQUEUE_PENDING : POSIX_TIMER_DISARMED;
357 	posixtimer_send_sigqueue(timr);
358 }
359 
360 /*
361  * This function gets called when a POSIX.1b interval timer expires from
362  * the HRTIMER interrupt (soft interrupt on RT kernels).
363  *
364  * Handles CLOCK_REALTIME, CLOCK_MONOTONIC, CLOCK_BOOTTIME and CLOCK_TAI
365  * based timers.
366  */
367 static enum hrtimer_restart posix_timer_fn(struct hrtimer *timer)
368 {
369 	struct k_itimer *timr = container_of(timer, struct k_itimer, it.real.timer);
370 
371 	guard(spinlock_irqsave)(&timr->it_lock);
372 	posix_timer_queue_signal(timr);
373 	return HRTIMER_NORESTART;
374 }
375 
376 long posixtimer_create_prctl(unsigned long ctrl)
377 {
378 	switch (ctrl) {
379 	case PR_TIMER_CREATE_RESTORE_IDS_OFF:
380 		current->signal->timer_create_restore_ids = 0;
381 		return 0;
382 	case PR_TIMER_CREATE_RESTORE_IDS_ON:
383 		current->signal->timer_create_restore_ids = 1;
384 		return 0;
385 	case PR_TIMER_CREATE_RESTORE_IDS_GET:
386 		return current->signal->timer_create_restore_ids;
387 	}
388 	return -EINVAL;
389 }
390 
391 static struct pid *good_sigevent(sigevent_t * event)
392 {
393 	struct pid *pid = task_tgid(current);
394 	struct task_struct *rtn;
395 
396 	switch (event->sigev_notify) {
397 	case SIGEV_SIGNAL | SIGEV_THREAD_ID:
398 		pid = find_vpid(event->sigev_notify_thread_id);
399 		rtn = pid_task(pid, PIDTYPE_PID);
400 		if (!rtn || !same_thread_group(rtn, current))
401 			return NULL;
402 		fallthrough;
403 	case SIGEV_SIGNAL:
404 	case SIGEV_THREAD:
405 		if (event->sigev_signo <= 0 || event->sigev_signo > SIGRTMAX)
406 			return NULL;
407 		fallthrough;
408 	case SIGEV_NONE:
409 		return pid;
410 	default:
411 		return NULL;
412 	}
413 }
414 
415 static struct k_itimer *alloc_posix_timer(void)
416 {
417 	struct k_itimer *tmr;
418 
419 	if (unlikely(!posix_timers_cache))
420 		return NULL;
421 
422 	tmr = kmem_cache_zalloc(posix_timers_cache, GFP_KERNEL);
423 	if (!tmr)
424 		return tmr;
425 
426 	if (unlikely(!posixtimer_init_sigqueue(&tmr->sigq))) {
427 		kmem_cache_free(posix_timers_cache, tmr);
428 		return NULL;
429 	}
430 	rcuref_init(&tmr->rcuref, 1);
431 	return tmr;
432 }
433 
434 void posixtimer_free_timer(struct k_itimer *tmr)
435 {
436 	put_pid(tmr->it_pid);
437 	if (tmr->sigq.ucounts)
438 		dec_rlimit_put_ucounts(tmr->sigq.ucounts, UCOUNT_RLIMIT_SIGPENDING);
439 	kfree_rcu(tmr, rcu);
440 }
441 
442 static void posix_timer_unhash_and_free(struct k_itimer *tmr)
443 {
444 	struct timer_hash_bucket *bucket = hash_bucket(posix_sig_owner(tmr), tmr->it_id);
445 
446 	scoped_guard (spinlock, &bucket->lock)
447 		hlist_del_rcu(&tmr->t_hash);
448 	posixtimer_putref(tmr);
449 }
450 
451 static int common_timer_create(struct k_itimer *new_timer)
452 {
453 	hrtimer_setup(&new_timer->it.real.timer, posix_timer_fn, new_timer->it_clock, 0);
454 	return 0;
455 }
456 
457 /* Create a POSIX.1b interval timer. */
458 static int do_timer_create(clockid_t which_clock, struct sigevent *event,
459 			   timer_t __user *created_timer_id)
460 {
461 	const struct k_clock *kc = clockid_to_kclock(which_clock);
462 	timer_t req_id = TIMER_ANY_ID;
463 	struct k_itimer *new_timer;
464 	int error, new_timer_id;
465 
466 	if (!kc)
467 		return -EINVAL;
468 	if (!kc->timer_create)
469 		return -EOPNOTSUPP;
470 
471 	/* Special case for CRIU to restore timers with a given timer ID. */
472 	if (unlikely(current->signal->timer_create_restore_ids)) {
473 		if (copy_from_user(&req_id, created_timer_id, sizeof(req_id)))
474 			return -EFAULT;
475 		/* Valid IDs are 0..INT_MAX */
476 		if ((unsigned int)req_id > INT_MAX)
477 			return -EINVAL;
478 	}
479 
480 	new_timer = alloc_posix_timer();
481 	if (unlikely(!new_timer))
482 		return -EAGAIN;
483 
484 	spin_lock_init(&new_timer->it_lock);
485 
486 	/*
487 	 * Add the timer to the hash table. The timer is not yet valid
488 	 * after insertion, but has a unique ID allocated.
489 	 */
490 	new_timer_id = posix_timer_add(new_timer, req_id);
491 	if (new_timer_id < 0) {
492 		posixtimer_free_timer(new_timer);
493 		return new_timer_id;
494 	}
495 
496 	new_timer->it_clock = which_clock;
497 	new_timer->kclock = kc;
498 	new_timer->it_overrun = -1LL;
499 
500 	if (event) {
501 		scoped_guard (rcu)
502 			new_timer->it_pid = get_pid(good_sigevent(event));
503 		if (!new_timer->it_pid) {
504 			error = -EINVAL;
505 			goto out;
506 		}
507 		new_timer->it_sigev_notify     = event->sigev_notify;
508 		new_timer->sigq.info.si_signo = event->sigev_signo;
509 		new_timer->sigq.info.si_value = event->sigev_value;
510 	} else {
511 		new_timer->it_sigev_notify     = SIGEV_SIGNAL;
512 		new_timer->sigq.info.si_signo = SIGALRM;
513 		new_timer->sigq.info.si_value.sival_int = new_timer->it_id;
514 		new_timer->it_pid = get_pid(task_tgid(current));
515 	}
516 
517 	if (new_timer->it_sigev_notify & SIGEV_THREAD_ID)
518 		new_timer->it_pid_type = PIDTYPE_PID;
519 	else
520 		new_timer->it_pid_type = PIDTYPE_TGID;
521 
522 	new_timer->sigq.info.si_tid = new_timer->it_id;
523 	new_timer->sigq.info.si_code = SI_TIMER;
524 
525 	if (copy_to_user(created_timer_id, &new_timer_id, sizeof (new_timer_id))) {
526 		error = -EFAULT;
527 		goto out;
528 	}
529 	/*
530 	 * After successful copy out, the timer ID is visible to user space
531 	 * now but not yet valid because new_timer::signal low order bit is 1.
532 	 *
533 	 * Complete the initialization with the clock specific create
534 	 * callback.
535 	 */
536 	error = kc->timer_create(new_timer);
537 	if (error)
538 		goto out;
539 
540 	/*
541 	 * timer::it_lock ensures that __lock_timer() observes a fully
542 	 * initialized timer when it observes a valid timer::it_signal.
543 	 *
544 	 * sighand::siglock is required to protect signal::posix_timers.
545 	 */
546 	scoped_guard (spinlock_irq, &new_timer->it_lock) {
547 		guard(spinlock)(&current->sighand->siglock);
548 		/*
549 		 * new_timer::it_signal contains the signal pointer with
550 		 * bit 0 set, which makes it invalid for syscall operations.
551 		 * Store the unmodified signal pointer to make it valid.
552 		 */
553 		WRITE_ONCE(new_timer->it_signal, current->signal);
554 		hlist_add_head_rcu(&new_timer->list, &current->signal->posix_timers);
555 	}
556 	/*
557 	 * After unlocking @new_timer is subject to concurrent removal and
558 	 * cannot be touched anymore
559 	 */
560 	return 0;
561 out:
562 	posix_timer_unhash_and_free(new_timer);
563 	return error;
564 }
565 
566 SYSCALL_DEFINE3(timer_create, const clockid_t, which_clock,
567 		struct sigevent __user *, timer_event_spec,
568 		timer_t __user *, created_timer_id)
569 {
570 	if (timer_event_spec) {
571 		sigevent_t event;
572 
573 		if (copy_from_user(&event, timer_event_spec, sizeof (event)))
574 			return -EFAULT;
575 		return do_timer_create(which_clock, &event, created_timer_id);
576 	}
577 	return do_timer_create(which_clock, NULL, created_timer_id);
578 }
579 
580 #ifdef CONFIG_COMPAT
581 COMPAT_SYSCALL_DEFINE3(timer_create, clockid_t, which_clock,
582 		       struct compat_sigevent __user *, timer_event_spec,
583 		       timer_t __user *, created_timer_id)
584 {
585 	if (timer_event_spec) {
586 		sigevent_t event;
587 
588 		if (get_compat_sigevent(&event, timer_event_spec))
589 			return -EFAULT;
590 		return do_timer_create(which_clock, &event, created_timer_id);
591 	}
592 	return do_timer_create(which_clock, NULL, created_timer_id);
593 }
594 #endif
595 
596 static struct k_itimer *lock_timer(timer_t timer_id)
597 {
598 	struct k_itimer *timr;
599 
600 	/*
601 	 * timer_t could be any type >= int and we want to make sure any
602 	 * @timer_id outside positive int range fails lookup.
603 	 */
604 	if ((unsigned long long)timer_id > INT_MAX)
605 		return NULL;
606 
607 	/*
608 	 * The hash lookup and the timers are RCU protected.
609 	 *
610 	 * Timers are added to the hash in invalid state where
611 	 * timr::it_signal is marked invalid. timer::it_signal is only set
612 	 * after the rest of the initialization succeeded.
613 	 *
614 	 * Timer destruction happens in steps:
615 	 *  1) Set timr::it_signal marked invalid with timr::it_lock held
616 	 *  2) Release timr::it_lock
617 	 *  3) Remove from the hash under hash_lock
618 	 *  4) Put the reference count.
619 	 *
620 	 * The reference count might not drop to zero if timr::sigq is
621 	 * queued. In that case the signal delivery or flush will put the
622 	 * last reference count.
623 	 *
624 	 * When the reference count reaches zero, the timer is scheduled
625 	 * for RCU removal after the grace period.
626 	 *
627 	 * Holding rcu_read_lock() across the lookup ensures that
628 	 * the timer cannot be freed.
629 	 *
630 	 * The lookup validates locklessly that timr::it_signal ==
631 	 * current::it_signal and timr::it_id == @timer_id. timr::it_id
632 	 * can't change, but timr::it_signal can become invalid during
633 	 * destruction, which makes the locked check fail.
634 	 */
635 	guard(rcu)();
636 	timr = posix_timer_by_id(timer_id);
637 	if (timr) {
638 		spin_lock_irq(&timr->it_lock);
639 		/*
640 		 * Validate under timr::it_lock that timr::it_signal is
641 		 * still valid. Pairs with #1 above.
642 		 */
643 		if (timr->it_signal == current->signal)
644 			return timr;
645 		spin_unlock_irq(&timr->it_lock);
646 	}
647 	return NULL;
648 }
649 
650 static ktime_t common_hrtimer_remaining(struct k_itimer *timr, ktime_t now)
651 {
652 	struct hrtimer *timer = &timr->it.real.timer;
653 
654 	return __hrtimer_expires_remaining_adjusted(timer, now);
655 }
656 
657 static s64 common_hrtimer_forward(struct k_itimer *timr, ktime_t now)
658 {
659 	struct hrtimer *timer = &timr->it.real.timer;
660 
661 	return hrtimer_forward(timer, now, timr->it_interval);
662 }
663 
664 /*
665  * Get the time remaining on a POSIX.1b interval timer.
666  *
667  * Two issues to handle here:
668  *
669  *  1) The timer has a requeue pending. The return value must appear as
670  *     if the timer has been requeued right now.
671  *
672  *  2) The timer is a SIGEV_NONE timer. These timers are never enqueued
673  *     into the hrtimer queue and therefore never expired. Emulate expiry
674  *     here taking #1 into account.
675  */
676 void common_timer_get(struct k_itimer *timr, struct itimerspec64 *cur_setting)
677 {
678 	const struct k_clock *kc = timr->kclock;
679 	ktime_t now, remaining, iv;
680 	bool sig_none;
681 
682 	sig_none = timr->it_sigev_notify == SIGEV_NONE;
683 	iv = timr->it_interval;
684 
685 	/* interval timer ? */
686 	if (iv) {
687 		cur_setting->it_interval = ktime_to_timespec64(iv);
688 	} else if (timr->it_status == POSIX_TIMER_DISARMED) {
689 		/*
690 		 * SIGEV_NONE oneshot timers are never queued and therefore
691 		 * timr->it_status is always DISARMED. The check below
692 		 * vs. remaining time will handle this case.
693 		 *
694 		 * For all other timers there is nothing to update here, so
695 		 * return.
696 		 */
697 		if (!sig_none)
698 			return;
699 	}
700 
701 	now = kc->clock_get_ktime(timr->it_clock);
702 
703 	/*
704 	 * If this is an interval timer and either has requeue pending or
705 	 * is a SIGEV_NONE timer move the expiry time forward by intervals,
706 	 * so expiry is > now.
707 	 */
708 	if (iv && timr->it_status != POSIX_TIMER_ARMED)
709 		timr->it_overrun += kc->timer_forward(timr, now);
710 
711 	remaining = kc->timer_remaining(timr, now);
712 	/*
713 	 * As @now is retrieved before a possible timer_forward() and
714 	 * cannot be reevaluated by the compiler @remaining is based on the
715 	 * same @now value. Therefore @remaining is consistent vs. @now.
716 	 *
717 	 * Consequently all interval timers, i.e. @iv > 0, cannot have a
718 	 * remaining time <= 0 because timer_forward() guarantees to move
719 	 * them forward so that the next timer expiry is > @now.
720 	 */
721 	if (remaining <= 0) {
722 		/*
723 		 * A single shot SIGEV_NONE timer must return 0, when it is
724 		 * expired! Timers which have a real signal delivery mode
725 		 * must return a remaining time greater than 0 because the
726 		 * signal has not yet been delivered.
727 		 */
728 		if (!sig_none)
729 			cur_setting->it_value.tv_nsec = 1;
730 	} else {
731 		cur_setting->it_value = ktime_to_timespec64(remaining);
732 	}
733 }
734 
735 static int do_timer_gettime(timer_t timer_id,  struct itimerspec64 *setting)
736 {
737 	memset(setting, 0, sizeof(*setting));
738 	scoped_timer_get_or_fail(timer_id)
739 		scoped_timer->kclock->timer_get(scoped_timer, setting);
740 	return 0;
741 }
742 
743 /* Get the time remaining on a POSIX.1b interval timer. */
744 SYSCALL_DEFINE2(timer_gettime, timer_t, timer_id,
745 		struct __kernel_itimerspec __user *, setting)
746 {
747 	struct itimerspec64 cur_setting;
748 
749 	int ret = do_timer_gettime(timer_id, &cur_setting);
750 	if (!ret) {
751 		if (put_itimerspec64(&cur_setting, setting))
752 			ret = -EFAULT;
753 	}
754 	return ret;
755 }
756 
757 #ifdef CONFIG_COMPAT_32BIT_TIME
758 
759 SYSCALL_DEFINE2(timer_gettime32, timer_t, timer_id,
760 		struct old_itimerspec32 __user *, setting)
761 {
762 	struct itimerspec64 cur_setting;
763 
764 	int ret = do_timer_gettime(timer_id, &cur_setting);
765 	if (!ret) {
766 		if (put_old_itimerspec32(&cur_setting, setting))
767 			ret = -EFAULT;
768 	}
769 	return ret;
770 }
771 
772 #endif
773 
774 /**
775  * sys_timer_getoverrun - Get the number of overruns of a POSIX.1b interval timer
776  * @timer_id:	The timer ID which identifies the timer
777  *
778  * The "overrun count" of a timer is one plus the number of expiration
779  * intervals which have elapsed between the first expiry, which queues the
780  * signal and the actual signal delivery. On signal delivery the "overrun
781  * count" is calculated and cached, so it can be returned directly here.
782  *
783  * As this is relative to the last queued signal the returned overrun count
784  * is meaningless outside of the signal delivery path and even there it
785  * does not accurately reflect the current state when user space evaluates
786  * it.
787  *
788  * Returns:
789  *	-EINVAL		@timer_id is invalid
790  *	1..INT_MAX	The number of overruns related to the last delivered signal
791  */
792 SYSCALL_DEFINE1(timer_getoverrun, timer_t, timer_id)
793 {
794 	scoped_timer_get_or_fail(timer_id)
795 		return timer_overrun_to_int(scoped_timer);
796 }
797 
798 static void common_hrtimer_arm(struct k_itimer *timr, ktime_t expires,
799 			       bool absolute, bool sigev_none)
800 {
801 	struct hrtimer *timer = &timr->it.real.timer;
802 	enum hrtimer_mode mode;
803 
804 	mode = absolute ? HRTIMER_MODE_ABS : HRTIMER_MODE_REL;
805 	/*
806 	 * Posix magic: Relative CLOCK_REALTIME timers are not affected by
807 	 * clock modifications, so they become CLOCK_MONOTONIC based under the
808 	 * hood. See hrtimer_setup(). Update timr->kclock, so the generic
809 	 * functions which use timr->kclock->clock_get_*() work.
810 	 *
811 	 * Note: it_clock stays unmodified, because the next timer_set() might
812 	 * use ABSTIME, so it needs to switch back.
813 	 */
814 	if (timr->it_clock == CLOCK_REALTIME)
815 		timr->kclock = absolute ? &clock_realtime : &clock_monotonic;
816 
817 	hrtimer_setup(&timr->it.real.timer, posix_timer_fn, timr->it_clock, mode);
818 
819 	if (!absolute)
820 		expires = ktime_add_safe(expires, hrtimer_cb_get_time(timer));
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 static void common_timer_wait_running(struct k_itimer *timer)
833 {
834 	hrtimer_cancel_wait_running(&timer->it.real.timer);
835 }
836 
837 /*
838  * On PREEMPT_RT this prevents priority inversion and a potential livelock
839  * against the ksoftirqd thread in case that ksoftirqd gets preempted while
840  * executing a hrtimer callback.
841  *
842  * See the comments in hrtimer_cancel_wait_running(). For PREEMPT_RT=n this
843  * just results in a cpu_relax().
844  *
845  * For POSIX CPU timers with CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n this is
846  * just a cpu_relax(). With CONFIG_POSIX_CPU_TIMERS_TASK_WORK=y this
847  * prevents spinning on an eventually scheduled out task and a livelock
848  * when the task which tries to delete or disarm the timer has preempted
849  * the task which runs the expiry in task work context.
850  */
851 static void timer_wait_running(struct k_itimer *timer)
852 {
853 	/*
854 	 * kc->timer_wait_running() might drop RCU lock. So @timer
855 	 * cannot be touched anymore after the function returns!
856 	 */
857 	timer->kclock->timer_wait_running(timer);
858 }
859 
860 /*
861  * Set up the new interval and reset the signal delivery data
862  */
863 void posix_timer_set_common(struct k_itimer *timer, struct itimerspec64 *new_setting)
864 {
865 	if (new_setting->it_value.tv_sec || new_setting->it_value.tv_nsec)
866 		timer->it_interval = timespec64_to_ktime(new_setting->it_interval);
867 	else
868 		timer->it_interval = 0;
869 
870 	/* Reset overrun accounting */
871 	timer->it_overrun_last = 0;
872 	timer->it_overrun = -1LL;
873 }
874 
875 /* Set a POSIX.1b interval timer. */
876 int common_timer_set(struct k_itimer *timr, int flags,
877 		     struct itimerspec64 *new_setting,
878 		     struct itimerspec64 *old_setting)
879 {
880 	const struct k_clock *kc = timr->kclock;
881 	bool sigev_none;
882 	ktime_t expires;
883 
884 	if (old_setting)
885 		common_timer_get(timr, old_setting);
886 
887 	/*
888 	 * Careful here. On SMP systems the timer expiry function could be
889 	 * active and spinning on timr->it_lock.
890 	 */
891 	if (kc->timer_try_to_cancel(timr) < 0)
892 		return TIMER_RETRY;
893 
894 	timr->it_status = POSIX_TIMER_DISARMED;
895 	posix_timer_set_common(timr, new_setting);
896 
897 	/* Keep timer disarmed when it_value is zero */
898 	if (!new_setting->it_value.tv_sec && !new_setting->it_value.tv_nsec)
899 		return 0;
900 
901 	expires = timespec64_to_ktime(new_setting->it_value);
902 	if (flags & TIMER_ABSTIME)
903 		expires = timens_ktime_to_host(timr->it_clock, expires);
904 	sigev_none = timr->it_sigev_notify == SIGEV_NONE;
905 
906 	kc->timer_arm(timr, expires, flags & TIMER_ABSTIME, sigev_none);
907 	if (!sigev_none)
908 		timr->it_status = POSIX_TIMER_ARMED;
909 	return 0;
910 }
911 
912 static int do_timer_settime(timer_t timer_id, int tmr_flags, struct itimerspec64 *new_spec64,
913 			    struct itimerspec64 *old_spec64)
914 {
915 	if (!timespec64_valid(&new_spec64->it_interval) ||
916 	    !timespec64_valid(&new_spec64->it_value))
917 		return -EINVAL;
918 
919 	if (old_spec64)
920 		memset(old_spec64, 0, sizeof(*old_spec64));
921 
922 	for (; ; old_spec64 = NULL) {
923 		struct k_itimer *timr;
924 
925 		scoped_timer_get_or_fail(timer_id) {
926 			timr = scoped_timer;
927 
928 			if (old_spec64)
929 				old_spec64->it_interval = ktime_to_timespec64(timr->it_interval);
930 
931 			/* Prevent signal delivery and rearming. */
932 			timr->it_signal_seq++;
933 
934 			int ret = timr->kclock->timer_set(timr, tmr_flags, new_spec64, old_spec64);
935 			if (ret != TIMER_RETRY)
936 				return ret;
937 
938 			/* Protect the timer from being freed when leaving the lock scope */
939 			rcu_read_lock();
940 		}
941 		timer_wait_running(timr);
942 		rcu_read_unlock();
943 	}
944 }
945 
946 /* Set a POSIX.1b interval timer */
947 SYSCALL_DEFINE4(timer_settime, timer_t, timer_id, int, flags,
948 		const struct __kernel_itimerspec __user *, new_setting,
949 		struct __kernel_itimerspec __user *, old_setting)
950 {
951 	struct itimerspec64 new_spec, old_spec, *rtn;
952 	int error = 0;
953 
954 	if (!new_setting)
955 		return -EINVAL;
956 
957 	if (get_itimerspec64(&new_spec, new_setting))
958 		return -EFAULT;
959 
960 	rtn = old_setting ? &old_spec : NULL;
961 	error = do_timer_settime(timer_id, flags, &new_spec, rtn);
962 	if (!error && old_setting) {
963 		if (put_itimerspec64(&old_spec, old_setting))
964 			error = -EFAULT;
965 	}
966 	return error;
967 }
968 
969 #ifdef CONFIG_COMPAT_32BIT_TIME
970 SYSCALL_DEFINE4(timer_settime32, timer_t, timer_id, int, flags,
971 		struct old_itimerspec32 __user *, new,
972 		struct old_itimerspec32 __user *, old)
973 {
974 	struct itimerspec64 new_spec, old_spec;
975 	struct itimerspec64 *rtn = old ? &old_spec : NULL;
976 	int error = 0;
977 
978 	if (!new)
979 		return -EINVAL;
980 	if (get_old_itimerspec32(&new_spec, new))
981 		return -EFAULT;
982 
983 	error = do_timer_settime(timer_id, flags, &new_spec, rtn);
984 	if (!error && old) {
985 		if (put_old_itimerspec32(&old_spec, old))
986 			error = -EFAULT;
987 	}
988 	return error;
989 }
990 #endif
991 
992 int common_timer_del(struct k_itimer *timer)
993 {
994 	const struct k_clock *kc = timer->kclock;
995 
996 	if (kc->timer_try_to_cancel(timer) < 0)
997 		return TIMER_RETRY;
998 	timer->it_status = POSIX_TIMER_DISARMED;
999 	return 0;
1000 }
1001 
1002 /*
1003  * If the deleted timer is on the ignored list, remove it and
1004  * drop the associated reference.
1005  */
1006 static inline void posix_timer_cleanup_ignored(struct k_itimer *tmr)
1007 {
1008 	if (!hlist_unhashed(&tmr->ignored_list)) {
1009 		hlist_del_init(&tmr->ignored_list);
1010 		posixtimer_putref(tmr);
1011 	}
1012 }
1013 
1014 static void posix_timer_delete(struct k_itimer *timer)
1015 {
1016 	/*
1017 	 * Invalidate the timer, remove it from the linked list and remove
1018 	 * it from the ignored list if pending.
1019 	 *
1020 	 * The invalidation must be written with siglock held so that the
1021 	 * signal code observes the invalidated timer::it_signal in
1022 	 * do_sigaction(), which prevents it from moving a pending signal
1023 	 * of a deleted timer to the ignore list.
1024 	 *
1025 	 * The invalidation also prevents signal queueing, signal delivery
1026 	 * and therefore rearming from the signal delivery path.
1027 	 *
1028 	 * A concurrent lookup can still find the timer in the hash, but it
1029 	 * will check timer::it_signal with timer::it_lock held and observe
1030 	 * bit 0 set, which invalidates it. That also prevents the timer ID
1031 	 * from being handed out before this timer is completely gone.
1032 	 */
1033 	timer->it_signal_seq++;
1034 
1035 	scoped_guard (spinlock, &current->sighand->siglock) {
1036 		unsigned long sig = (unsigned long)timer->it_signal | 1UL;
1037 
1038 		WRITE_ONCE(timer->it_signal, (struct signal_struct *)sig);
1039 		hlist_del_rcu(&timer->list);
1040 		posix_timer_cleanup_ignored(timer);
1041 	}
1042 
1043 	while (timer->kclock->timer_del(timer) == TIMER_RETRY) {
1044 		guard(rcu)();
1045 		spin_unlock_irq(&timer->it_lock);
1046 		timer_wait_running(timer);
1047 		spin_lock_irq(&timer->it_lock);
1048 	}
1049 }
1050 
1051 /* Delete a POSIX.1b interval timer. */
1052 SYSCALL_DEFINE1(timer_delete, timer_t, timer_id)
1053 {
1054 	struct k_itimer *timer;
1055 
1056 	scoped_timer_get_or_fail(timer_id) {
1057 		timer = scoped_timer;
1058 		posix_timer_delete(timer);
1059 	}
1060 	/* Remove it from the hash, which frees up the timer ID */
1061 	posix_timer_unhash_and_free(timer);
1062 	return 0;
1063 }
1064 
1065 /*
1066  * Invoked from do_exit() when the last thread of a thread group exits.
1067  * At that point no other task can access the timers of the dying
1068  * task anymore.
1069  */
1070 void exit_itimers(struct task_struct *tsk)
1071 {
1072 	struct hlist_head timers;
1073 	struct hlist_node *next;
1074 	struct k_itimer *timer;
1075 
1076 	/* Clear restore mode for exec() */
1077 	tsk->signal->timer_create_restore_ids = 0;
1078 
1079 	if (hlist_empty(&tsk->signal->posix_timers))
1080 		return;
1081 
1082 	/* Protect against concurrent read via /proc/$PID/timers */
1083 	scoped_guard (spinlock_irq, &tsk->sighand->siglock)
1084 		hlist_move_list(&tsk->signal->posix_timers, &timers);
1085 
1086 	/* The timers are not longer accessible via tsk::signal */
1087 	hlist_for_each_entry_safe(timer, next, &timers, list) {
1088 		scoped_guard (spinlock_irq, &timer->it_lock)
1089 			posix_timer_delete(timer);
1090 		posix_timer_unhash_and_free(timer);
1091 		cond_resched();
1092 	}
1093 
1094 	/*
1095 	 * There should be no timers on the ignored list. itimer_delete() has
1096 	 * mopped them up.
1097 	 */
1098 	if (!WARN_ON_ONCE(!hlist_empty(&tsk->signal->ignored_posix_timers)))
1099 		return;
1100 
1101 	hlist_move_list(&tsk->signal->ignored_posix_timers, &timers);
1102 	while (!hlist_empty(&timers)) {
1103 		posix_timer_cleanup_ignored(hlist_entry(timers.first, struct k_itimer,
1104 							ignored_list));
1105 	}
1106 }
1107 
1108 SYSCALL_DEFINE2(clock_settime, const clockid_t, which_clock,
1109 		const struct __kernel_timespec __user *, tp)
1110 {
1111 	const struct k_clock *kc = clockid_to_kclock(which_clock);
1112 	struct timespec64 new_tp;
1113 
1114 	if (!kc || !kc->clock_set)
1115 		return -EINVAL;
1116 
1117 	if (get_timespec64(&new_tp, tp))
1118 		return -EFAULT;
1119 
1120 	/*
1121 	 * Permission checks have to be done inside the clock specific
1122 	 * setter callback.
1123 	 */
1124 	return kc->clock_set(which_clock, &new_tp);
1125 }
1126 
1127 SYSCALL_DEFINE2(clock_gettime, const clockid_t, which_clock,
1128 		struct __kernel_timespec __user *, tp)
1129 {
1130 	const struct k_clock *kc = clockid_to_kclock(which_clock);
1131 	struct timespec64 kernel_tp;
1132 	int error;
1133 
1134 	if (!kc)
1135 		return -EINVAL;
1136 
1137 	error = kc->clock_get_timespec(which_clock, &kernel_tp);
1138 
1139 	if (!error && put_timespec64(&kernel_tp, tp))
1140 		error = -EFAULT;
1141 
1142 	return error;
1143 }
1144 
1145 int do_clock_adjtime(const clockid_t which_clock, struct __kernel_timex * ktx)
1146 {
1147 	const struct k_clock *kc = clockid_to_kclock(which_clock);
1148 
1149 	if (!kc)
1150 		return -EINVAL;
1151 	if (!kc->clock_adj)
1152 		return -EOPNOTSUPP;
1153 
1154 	return kc->clock_adj(which_clock, ktx);
1155 }
1156 
1157 SYSCALL_DEFINE2(clock_adjtime, const clockid_t, which_clock,
1158 		struct __kernel_timex __user *, utx)
1159 {
1160 	struct __kernel_timex ktx;
1161 	int err;
1162 
1163 	if (copy_from_user(&ktx, utx, sizeof(ktx)))
1164 		return -EFAULT;
1165 
1166 	err = do_clock_adjtime(which_clock, &ktx);
1167 
1168 	if (err >= 0 && copy_to_user(utx, &ktx, sizeof(ktx)))
1169 		return -EFAULT;
1170 
1171 	return err;
1172 }
1173 
1174 /**
1175  * sys_clock_getres - Get the resolution of a clock
1176  * @which_clock:	The clock to get the resolution for
1177  * @tp:			Pointer to a a user space timespec64 for storage
1178  *
1179  * POSIX defines:
1180  *
1181  * "The clock_getres() function shall return the resolution of any
1182  * clock. Clock resolutions are implementation-defined and cannot be set by
1183  * a process. If the argument res is not NULL, the resolution of the
1184  * specified clock shall be stored in the location pointed to by res. If
1185  * res is NULL, the clock resolution is not returned. If the time argument
1186  * of clock_settime() is not a multiple of res, then the value is truncated
1187  * to a multiple of res."
1188  *
1189  * Due to the various hardware constraints the real resolution can vary
1190  * wildly and even change during runtime when the underlying devices are
1191  * replaced. The kernel also can use hardware devices with different
1192  * resolutions for reading the time and for arming timers.
1193  *
1194  * The kernel therefore deviates from the POSIX spec in various aspects:
1195  *
1196  * 1) The resolution returned to user space
1197  *
1198  *    For CLOCK_REALTIME, CLOCK_MONOTONIC, CLOCK_BOOTTIME, CLOCK_TAI,
1199  *    CLOCK_REALTIME_ALARM, CLOCK_BOOTTIME_ALAREM and CLOCK_MONOTONIC_RAW
1200  *    the kernel differentiates only two cases:
1201  *
1202  *    I)  Low resolution mode:
1203  *
1204  *	  When high resolution timers are disabled at compile or runtime
1205  *	  the resolution returned is nanoseconds per tick, which represents
1206  *	  the precision at which timers expire.
1207  *
1208  *    II) High resolution mode:
1209  *
1210  *	  When high resolution timers are enabled the resolution returned
1211  *	  is always one nanosecond independent of the actual resolution of
1212  *	  the underlying hardware devices.
1213  *
1214  *	  For CLOCK_*_ALARM the actual resolution depends on system
1215  *	  state. When system is running the resolution is the same as the
1216  *	  resolution of the other clocks. During suspend the actual
1217  *	  resolution is the resolution of the underlying RTC device which
1218  *	  might be way less precise than the clockevent device used during
1219  *	  running state.
1220  *
1221  *   For CLOCK_REALTIME_COARSE and CLOCK_MONOTONIC_COARSE the resolution
1222  *   returned is always nanoseconds per tick.
1223  *
1224  *   For CLOCK_PROCESS_CPUTIME and CLOCK_THREAD_CPUTIME the resolution
1225  *   returned is always one nanosecond under the assumption that the
1226  *   underlying scheduler clock has a better resolution than nanoseconds
1227  *   per tick.
1228  *
1229  *   For dynamic POSIX clocks (PTP devices) the resolution returned is
1230  *   always one nanosecond.
1231  *
1232  * 2) Affect on sys_clock_settime()
1233  *
1234  *    The kernel does not truncate the time which is handed in to
1235  *    sys_clock_settime(). The kernel internal timekeeping is always using
1236  *    nanoseconds precision independent of the clocksource device which is
1237  *    used to read the time from. The resolution of that device only
1238  *    affects the precision of the time returned by sys_clock_gettime().
1239  *
1240  * Returns:
1241  *	0		Success. @tp contains the resolution
1242  *	-EINVAL		@which_clock is not a valid clock ID
1243  *	-EFAULT		Copying the resolution to @tp faulted
1244  *	-ENODEV		Dynamic POSIX clock is not backed by a device
1245  *	-EOPNOTSUPP	Dynamic POSIX clock does not support getres()
1246  */
1247 SYSCALL_DEFINE2(clock_getres, const clockid_t, which_clock,
1248 		struct __kernel_timespec __user *, tp)
1249 {
1250 	const struct k_clock *kc = clockid_to_kclock(which_clock);
1251 	struct timespec64 rtn_tp;
1252 	int error;
1253 
1254 	if (!kc)
1255 		return -EINVAL;
1256 
1257 	error = kc->clock_getres(which_clock, &rtn_tp);
1258 
1259 	if (!error && tp && put_timespec64(&rtn_tp, tp))
1260 		error = -EFAULT;
1261 
1262 	return error;
1263 }
1264 
1265 #ifdef CONFIG_COMPAT_32BIT_TIME
1266 
1267 SYSCALL_DEFINE2(clock_settime32, clockid_t, which_clock,
1268 		struct old_timespec32 __user *, tp)
1269 {
1270 	const struct k_clock *kc = clockid_to_kclock(which_clock);
1271 	struct timespec64 ts;
1272 
1273 	if (!kc || !kc->clock_set)
1274 		return -EINVAL;
1275 
1276 	if (get_old_timespec32(&ts, tp))
1277 		return -EFAULT;
1278 
1279 	return kc->clock_set(which_clock, &ts);
1280 }
1281 
1282 SYSCALL_DEFINE2(clock_gettime32, clockid_t, which_clock,
1283 		struct old_timespec32 __user *, tp)
1284 {
1285 	const struct k_clock *kc = clockid_to_kclock(which_clock);
1286 	struct timespec64 ts;
1287 	int err;
1288 
1289 	if (!kc)
1290 		return -EINVAL;
1291 
1292 	err = kc->clock_get_timespec(which_clock, &ts);
1293 
1294 	if (!err && put_old_timespec32(&ts, tp))
1295 		err = -EFAULT;
1296 
1297 	return err;
1298 }
1299 
1300 SYSCALL_DEFINE2(clock_adjtime32, clockid_t, which_clock,
1301 		struct old_timex32 __user *, utp)
1302 {
1303 	struct __kernel_timex ktx;
1304 	int err;
1305 
1306 	err = get_old_timex32(&ktx, utp);
1307 	if (err)
1308 		return err;
1309 
1310 	err = do_clock_adjtime(which_clock, &ktx);
1311 
1312 	if (err >= 0 && put_old_timex32(utp, &ktx))
1313 		return -EFAULT;
1314 
1315 	return err;
1316 }
1317 
1318 SYSCALL_DEFINE2(clock_getres_time32, clockid_t, which_clock,
1319 		struct old_timespec32 __user *, tp)
1320 {
1321 	const struct k_clock *kc = clockid_to_kclock(which_clock);
1322 	struct timespec64 ts;
1323 	int err;
1324 
1325 	if (!kc)
1326 		return -EINVAL;
1327 
1328 	err = kc->clock_getres(which_clock, &ts);
1329 	if (!err && tp && put_old_timespec32(&ts, tp))
1330 		return -EFAULT;
1331 
1332 	return err;
1333 }
1334 
1335 #endif
1336 
1337 /*
1338  * sys_clock_nanosleep() for CLOCK_REALTIME and CLOCK_TAI
1339  */
1340 static int common_nsleep(const clockid_t which_clock, int flags,
1341 			 const struct timespec64 *rqtp)
1342 {
1343 	ktime_t texp = timespec64_to_ktime(*rqtp);
1344 
1345 	return hrtimer_nanosleep(texp, flags & TIMER_ABSTIME ?
1346 				 HRTIMER_MODE_ABS : HRTIMER_MODE_REL,
1347 				 which_clock);
1348 }
1349 
1350 /*
1351  * sys_clock_nanosleep() for CLOCK_MONOTONIC and CLOCK_BOOTTIME
1352  *
1353  * Absolute nanosleeps for these clocks are time-namespace adjusted.
1354  */
1355 static int common_nsleep_timens(const clockid_t which_clock, int flags,
1356 				const struct timespec64 *rqtp)
1357 {
1358 	ktime_t texp = timespec64_to_ktime(*rqtp);
1359 
1360 	if (flags & TIMER_ABSTIME)
1361 		texp = timens_ktime_to_host(which_clock, texp);
1362 
1363 	return hrtimer_nanosleep(texp, flags & TIMER_ABSTIME ?
1364 				 HRTIMER_MODE_ABS : HRTIMER_MODE_REL,
1365 				 which_clock);
1366 }
1367 
1368 SYSCALL_DEFINE4(clock_nanosleep, const clockid_t, which_clock, int, flags,
1369 		const struct __kernel_timespec __user *, rqtp,
1370 		struct __kernel_timespec __user *, rmtp)
1371 {
1372 	const struct k_clock *kc = clockid_to_kclock(which_clock);
1373 	struct timespec64 t;
1374 
1375 	if (!kc)
1376 		return -EINVAL;
1377 	if (!kc->nsleep)
1378 		return -EOPNOTSUPP;
1379 
1380 	if (get_timespec64(&t, rqtp))
1381 		return -EFAULT;
1382 
1383 	if (!timespec64_valid(&t))
1384 		return -EINVAL;
1385 	if (flags & TIMER_ABSTIME)
1386 		rmtp = NULL;
1387 	current->restart_block.fn = do_no_restart_syscall;
1388 	current->restart_block.nanosleep.type = rmtp ? TT_NATIVE : TT_NONE;
1389 	current->restart_block.nanosleep.rmtp = rmtp;
1390 
1391 	return kc->nsleep(which_clock, flags, &t);
1392 }
1393 
1394 #ifdef CONFIG_COMPAT_32BIT_TIME
1395 
1396 SYSCALL_DEFINE4(clock_nanosleep_time32, clockid_t, which_clock, int, flags,
1397 		struct old_timespec32 __user *, rqtp,
1398 		struct old_timespec32 __user *, rmtp)
1399 {
1400 	const struct k_clock *kc = clockid_to_kclock(which_clock);
1401 	struct timespec64 t;
1402 
1403 	if (!kc)
1404 		return -EINVAL;
1405 	if (!kc->nsleep)
1406 		return -EOPNOTSUPP;
1407 
1408 	if (get_old_timespec32(&t, rqtp))
1409 		return -EFAULT;
1410 
1411 	if (!timespec64_valid(&t))
1412 		return -EINVAL;
1413 	if (flags & TIMER_ABSTIME)
1414 		rmtp = NULL;
1415 	current->restart_block.fn = do_no_restart_syscall;
1416 	current->restart_block.nanosleep.type = rmtp ? TT_COMPAT : TT_NONE;
1417 	current->restart_block.nanosleep.compat_rmtp = rmtp;
1418 
1419 	return kc->nsleep(which_clock, flags, &t);
1420 }
1421 
1422 #endif
1423 
1424 static const struct k_clock clock_realtime = {
1425 	.clock_getres		= posix_get_hrtimer_res,
1426 	.clock_get_timespec	= posix_get_realtime_timespec,
1427 	.clock_get_ktime	= posix_get_realtime_ktime,
1428 	.clock_set		= posix_clock_realtime_set,
1429 	.clock_adj		= posix_clock_realtime_adj,
1430 	.nsleep			= common_nsleep,
1431 	.timer_create		= common_timer_create,
1432 	.timer_set		= common_timer_set,
1433 	.timer_get		= common_timer_get,
1434 	.timer_del		= common_timer_del,
1435 	.timer_rearm		= common_hrtimer_rearm,
1436 	.timer_forward		= common_hrtimer_forward,
1437 	.timer_remaining	= common_hrtimer_remaining,
1438 	.timer_try_to_cancel	= common_hrtimer_try_to_cancel,
1439 	.timer_wait_running	= common_timer_wait_running,
1440 	.timer_arm		= common_hrtimer_arm,
1441 };
1442 
1443 static const struct k_clock clock_monotonic = {
1444 	.clock_getres		= posix_get_hrtimer_res,
1445 	.clock_get_timespec	= posix_get_monotonic_timespec,
1446 	.clock_get_ktime	= posix_get_monotonic_ktime,
1447 	.nsleep			= common_nsleep_timens,
1448 	.timer_create		= common_timer_create,
1449 	.timer_set		= common_timer_set,
1450 	.timer_get		= common_timer_get,
1451 	.timer_del		= common_timer_del,
1452 	.timer_rearm		= common_hrtimer_rearm,
1453 	.timer_forward		= common_hrtimer_forward,
1454 	.timer_remaining	= common_hrtimer_remaining,
1455 	.timer_try_to_cancel	= common_hrtimer_try_to_cancel,
1456 	.timer_wait_running	= common_timer_wait_running,
1457 	.timer_arm		= common_hrtimer_arm,
1458 };
1459 
1460 static const struct k_clock clock_monotonic_raw = {
1461 	.clock_getres		= posix_get_hrtimer_res,
1462 	.clock_get_timespec	= posix_get_monotonic_raw,
1463 };
1464 
1465 static const struct k_clock clock_realtime_coarse = {
1466 	.clock_getres		= posix_get_coarse_res,
1467 	.clock_get_timespec	= posix_get_realtime_coarse,
1468 };
1469 
1470 static const struct k_clock clock_monotonic_coarse = {
1471 	.clock_getres		= posix_get_coarse_res,
1472 	.clock_get_timespec	= posix_get_monotonic_coarse,
1473 };
1474 
1475 static const struct k_clock clock_tai = {
1476 	.clock_getres		= posix_get_hrtimer_res,
1477 	.clock_get_ktime	= posix_get_tai_ktime,
1478 	.clock_get_timespec	= posix_get_tai_timespec,
1479 	.nsleep			= common_nsleep,
1480 	.timer_create		= common_timer_create,
1481 	.timer_set		= common_timer_set,
1482 	.timer_get		= common_timer_get,
1483 	.timer_del		= common_timer_del,
1484 	.timer_rearm		= common_hrtimer_rearm,
1485 	.timer_forward		= common_hrtimer_forward,
1486 	.timer_remaining	= common_hrtimer_remaining,
1487 	.timer_try_to_cancel	= common_hrtimer_try_to_cancel,
1488 	.timer_wait_running	= common_timer_wait_running,
1489 	.timer_arm		= common_hrtimer_arm,
1490 };
1491 
1492 static const struct k_clock clock_boottime = {
1493 	.clock_getres		= posix_get_hrtimer_res,
1494 	.clock_get_ktime	= posix_get_boottime_ktime,
1495 	.clock_get_timespec	= posix_get_boottime_timespec,
1496 	.nsleep			= common_nsleep_timens,
1497 	.timer_create		= common_timer_create,
1498 	.timer_set		= common_timer_set,
1499 	.timer_get		= common_timer_get,
1500 	.timer_del		= common_timer_del,
1501 	.timer_rearm		= common_hrtimer_rearm,
1502 	.timer_forward		= common_hrtimer_forward,
1503 	.timer_remaining	= common_hrtimer_remaining,
1504 	.timer_try_to_cancel	= common_hrtimer_try_to_cancel,
1505 	.timer_wait_running	= common_timer_wait_running,
1506 	.timer_arm		= common_hrtimer_arm,
1507 };
1508 
1509 static const struct k_clock * const posix_clocks[] = {
1510 	[CLOCK_REALTIME]		= &clock_realtime,
1511 	[CLOCK_MONOTONIC]		= &clock_monotonic,
1512 	[CLOCK_PROCESS_CPUTIME_ID]	= &clock_process,
1513 	[CLOCK_THREAD_CPUTIME_ID]	= &clock_thread,
1514 	[CLOCK_MONOTONIC_RAW]		= &clock_monotonic_raw,
1515 	[CLOCK_REALTIME_COARSE]		= &clock_realtime_coarse,
1516 	[CLOCK_MONOTONIC_COARSE]	= &clock_monotonic_coarse,
1517 	[CLOCK_BOOTTIME]		= &clock_boottime,
1518 	[CLOCK_REALTIME_ALARM]		= &alarm_clock,
1519 	[CLOCK_BOOTTIME_ALARM]		= &alarm_clock,
1520 	[CLOCK_TAI]			= &clock_tai,
1521 #ifdef CONFIG_POSIX_AUX_CLOCKS
1522 	[CLOCK_AUX ... CLOCK_AUX_LAST]	= &clock_aux,
1523 #endif
1524 };
1525 
1526 static const struct k_clock *clockid_to_kclock(const clockid_t id)
1527 {
1528 	clockid_t idx = id;
1529 
1530 	if (id < 0) {
1531 		return (id & CLOCKFD_MASK) == CLOCKFD ?
1532 			&clock_posix_dynamic : &clock_posix_cpu;
1533 	}
1534 
1535 	if (id >= ARRAY_SIZE(posix_clocks))
1536 		return NULL;
1537 
1538 	return posix_clocks[array_index_nospec(idx, ARRAY_SIZE(posix_clocks))];
1539 }
1540 
1541 static int __init posixtimer_init(void)
1542 {
1543 	unsigned long i, size;
1544 	unsigned int shift;
1545 
1546 	posix_timers_cache = kmem_cache_create("posix_timers_cache",
1547 					       sizeof(struct k_itimer),
1548 					       __alignof__(struct k_itimer),
1549 					       SLAB_ACCOUNT, NULL);
1550 
1551 	if (IS_ENABLED(CONFIG_BASE_SMALL))
1552 		size = 512;
1553 	else
1554 		size = roundup_pow_of_two(512 * num_possible_cpus());
1555 
1556 	timer_buckets = alloc_large_system_hash("posixtimers", sizeof(*timer_buckets),
1557 						size, 0, 0, &shift, NULL, size, size);
1558 	size = 1UL << shift;
1559 	timer_hashmask = size - 1;
1560 
1561 	for (i = 0; i < size; i++) {
1562 		spin_lock_init(&timer_buckets[i].lock);
1563 		INIT_HLIST_HEAD(&timer_buckets[i].head);
1564 	}
1565 	return 0;
1566 }
1567 core_initcall(posixtimer_init);
1568