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