Home | History | Annotate | Line # | Download | only in kern
kern_time.c revision 1.226
      1 /*	$NetBSD: kern_time.c,v 1.226 2024/12/22 23:18:29 riastradh Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2000, 2004, 2005, 2007, 2008, 2009, 2020
      5  *     The NetBSD Foundation, Inc.
      6  * All rights reserved.
      7  *
      8  * This code is derived from software contributed to The NetBSD Foundation
      9  * by Christopher G. Demetriou, by Andrew Doran, and by Jason R. Thorpe.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  *
     20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     30  * POSSIBILITY OF SUCH DAMAGE.
     31  */
     32 
     33 /*
     34  * Copyright (c) 1982, 1986, 1989, 1993
     35  *	The Regents of the University of California.  All rights reserved.
     36  *
     37  * Redistribution and use in source and binary forms, with or without
     38  * modification, are permitted provided that the following conditions
     39  * are met:
     40  * 1. Redistributions of source code must retain the above copyright
     41  *    notice, this list of conditions and the following disclaimer.
     42  * 2. Redistributions in binary form must reproduce the above copyright
     43  *    notice, this list of conditions and the following disclaimer in the
     44  *    documentation and/or other materials provided with the distribution.
     45  * 3. Neither the name of the University nor the names of its contributors
     46  *    may be used to endorse or promote products derived from this software
     47  *    without specific prior written permission.
     48  *
     49  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     50  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     51  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     52  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     53  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     54  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     55  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     56  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     57  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     58  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     59  * SUCH DAMAGE.
     60  *
     61  *	@(#)kern_time.c	8.4 (Berkeley) 5/26/95
     62  */
     63 
     64 #include <sys/cdefs.h>
     65 __KERNEL_RCSID(0, "$NetBSD: kern_time.c,v 1.226 2024/12/22 23:18:29 riastradh Exp $");
     66 
     67 #include <sys/param.h>
     68 #include <sys/types.h>
     69 
     70 #include <sys/callout.h>
     71 #include <sys/cpu.h>
     72 #include <sys/errno.h>
     73 #include <sys/intr.h>
     74 #include <sys/kauth.h>
     75 #include <sys/kernel.h>
     76 #include <sys/kmem.h>
     77 #include <sys/lwp.h>
     78 #include <sys/mount.h>
     79 #include <sys/mutex.h>
     80 #include <sys/proc.h>
     81 #include <sys/queue.h>
     82 #include <sys/resourcevar.h>
     83 #include <sys/signal.h>
     84 #include <sys/signalvar.h>
     85 #include <sys/syscallargs.h>
     86 #include <sys/syslog.h>
     87 #include <sys/systm.h>
     88 #include <sys/timetc.h>
     89 #include <sys/timevar.h>
     90 #include <sys/timex.h>
     91 #include <sys/vnode.h>
     92 
     93 #include <machine/limits.h>
     94 
     95 kmutex_t	itimer_mutex __cacheline_aligned;	/* XXX static */
     96 static struct itlist itimer_realtime_changed_notify;
     97 
     98 static void	itimer_callout(void *);
     99 static void	ptimer_intr(void *);
    100 static void	*ptimer_sih __read_mostly;
    101 static TAILQ_HEAD(, ptimer) ptimer_queue;
    102 
    103 #define	CLOCK_VIRTUAL_P(clockid)	\
    104 	((clockid) == CLOCK_VIRTUAL || (clockid) == CLOCK_PROF)
    105 
    106 CTASSERT(ITIMER_REAL == CLOCK_REALTIME);
    107 CTASSERT(ITIMER_VIRTUAL == CLOCK_VIRTUAL);
    108 CTASSERT(ITIMER_PROF == CLOCK_PROF);
    109 CTASSERT(ITIMER_MONOTONIC == CLOCK_MONOTONIC);
    110 
    111 /*
    112  * Initialize timekeeping.
    113  */
    114 void
    115 time_init(void)
    116 {
    117 
    118 	mutex_init(&itimer_mutex, MUTEX_DEFAULT, IPL_SCHED);
    119 	LIST_INIT(&itimer_realtime_changed_notify);
    120 
    121 	TAILQ_INIT(&ptimer_queue);
    122 	ptimer_sih = softint_establish(SOFTINT_CLOCK | SOFTINT_MPSAFE,
    123 	    ptimer_intr, NULL);
    124 }
    125 
    126 /*
    127  * Check if the time will wrap if set to ts.
    128  *
    129  * ts - timespec describing the new time
    130  * delta - the delta between the current time and ts
    131  */
    132 bool
    133 time_wraps(struct timespec *ts, struct timespec *delta)
    134 {
    135 
    136 	/*
    137 	 * Don't allow the time to be set forward so far it
    138 	 * will wrap and become negative, thus allowing an
    139 	 * attacker to bypass the next check below.  The
    140 	 * cutoff is 1 year before rollover occurs, so even
    141 	 * if the attacker uses adjtime(2) to move the time
    142 	 * past the cutoff, it will take a very long time
    143 	 * to get to the wrap point.
    144 	 */
    145 	if ((ts->tv_sec > LLONG_MAX - 365*24*60*60) ||
    146 	    (delta->tv_sec < 0 || delta->tv_nsec < 0))
    147 		return true;
    148 
    149 	return false;
    150 }
    151 
    152 /*
    153  * itimer_lock:
    154  *
    155  *	Acquire the interval timer data lock.
    156  */
    157 void
    158 itimer_lock(void)
    159 {
    160 	mutex_spin_enter(&itimer_mutex);
    161 }
    162 
    163 /*
    164  * itimer_unlock:
    165  *
    166  *	Release the interval timer data lock.
    167  */
    168 void
    169 itimer_unlock(void)
    170 {
    171 	mutex_spin_exit(&itimer_mutex);
    172 }
    173 
    174 /*
    175  * itimer_lock_held:
    176  *
    177  *	Check that the interval timer lock is held for diagnostic
    178  *	assertions.
    179  */
    180 inline bool __diagused
    181 itimer_lock_held(void)
    182 {
    183 	return mutex_owned(&itimer_mutex);
    184 }
    185 
    186 /*
    187  * Time of day and interval timer support.
    188  *
    189  * These routines provide the kernel entry points to get and set
    190  * the time-of-day and per-process interval timers.  Subroutines
    191  * here provide support for adding and subtracting timeval structures
    192  * and decrementing interval timers, optionally reloading the interval
    193  * timers when they expire.
    194  */
    195 
    196 /* This function is used by clock_settime and settimeofday */
    197 static int
    198 settime1(struct proc *p, const struct timespec *ts, bool check_kauth)
    199 {
    200 	struct timespec delta, now;
    201 
    202 	/*
    203 	 * The time being set to an unreasonable value will cause
    204 	 * unreasonable system behaviour.
    205 	 */
    206 	if (ts->tv_sec < 0 || ts->tv_sec > (1LL << 36))
    207 		return EINVAL;
    208 
    209 	nanotime(&now);
    210 	timespecsub(ts, &now, &delta);
    211 
    212 	if (check_kauth && kauth_authorize_system(kauth_cred_get(),
    213 	    KAUTH_SYSTEM_TIME, KAUTH_REQ_SYSTEM_TIME_SYSTEM, __UNCONST(ts),
    214 	    &delta, KAUTH_ARG(check_kauth ? false : true)) != 0) {
    215 		return EPERM;
    216 	}
    217 
    218 #ifdef notyet
    219 	if ((delta.tv_sec < 86400) && securelevel > 0) { /* XXX elad - notyet */
    220 		return EPERM;
    221 	}
    222 #endif
    223 
    224 	tc_setclock(ts);
    225 
    226 	resettodr();
    227 
    228 	/*
    229 	 * Notify pending CLOCK_REALTIME timers about the real time change.
    230 	 * There may be inactive timers on this list, but this happens
    231 	 * comparatively less often than timers firing, and so it's better
    232 	 * to put the extra checks here than to complicate the other code
    233 	 * path.
    234 	 */
    235 	struct itimer *it;
    236 	itimer_lock();
    237 	LIST_FOREACH(it, &itimer_realtime_changed_notify, it_rtchgq) {
    238 		KASSERT(it->it_ops->ito_realtime_changed != NULL);
    239 		if (timespecisset(&it->it_time.it_value)) {
    240 			(*it->it_ops->ito_realtime_changed)(it);
    241 		}
    242 	}
    243 	itimer_unlock();
    244 
    245 	return 0;
    246 }
    247 
    248 int
    249 settime(struct proc *p, struct timespec *ts)
    250 {
    251 	return settime1(p, ts, true);
    252 }
    253 
    254 /* ARGSUSED */
    255 int
    256 sys___clock_gettime50(struct lwp *l,
    257     const struct sys___clock_gettime50_args *uap, register_t *retval)
    258 {
    259 	/* {
    260 		syscallarg(clockid_t) clock_id;
    261 		syscallarg(struct timespec *) tp;
    262 	} */
    263 	int error;
    264 	struct timespec ats;
    265 
    266 	error = clock_gettime1(SCARG(uap, clock_id), &ats);
    267 	if (error != 0)
    268 		return error;
    269 
    270 	return copyout(&ats, SCARG(uap, tp), sizeof(ats));
    271 }
    272 
    273 /* ARGSUSED */
    274 int
    275 sys___clock_settime50(struct lwp *l,
    276     const struct sys___clock_settime50_args *uap, register_t *retval)
    277 {
    278 	/* {
    279 		syscallarg(clockid_t) clock_id;
    280 		syscallarg(const struct timespec *) tp;
    281 	} */
    282 	int error;
    283 	struct timespec ats;
    284 
    285 	if ((error = copyin(SCARG(uap, tp), &ats, sizeof(ats))) != 0)
    286 		return error;
    287 
    288 	return clock_settime1(l->l_proc, SCARG(uap, clock_id), &ats, true);
    289 }
    290 
    291 
    292 int
    293 clock_settime1(struct proc *p, clockid_t clock_id, const struct timespec *tp,
    294     bool check_kauth)
    295 {
    296 	int error;
    297 
    298 	if (tp->tv_nsec < 0 || tp->tv_nsec >= 1000000000L)
    299 		return EINVAL;
    300 
    301 	switch (clock_id) {
    302 	case CLOCK_REALTIME:
    303 		if ((error = settime1(p, tp, check_kauth)) != 0)
    304 			return error;
    305 		break;
    306 	case CLOCK_MONOTONIC:
    307 		return EINVAL;	/* read-only clock */
    308 	default:
    309 		return EINVAL;
    310 	}
    311 
    312 	return 0;
    313 }
    314 
    315 int
    316 sys___clock_getres50(struct lwp *l, const struct sys___clock_getres50_args *uap,
    317     register_t *retval)
    318 {
    319 	/* {
    320 		syscallarg(clockid_t) clock_id;
    321 		syscallarg(struct timespec *) tp;
    322 	} */
    323 	struct timespec ts;
    324 	int error;
    325 
    326 	if ((error = clock_getres1(SCARG(uap, clock_id), &ts)) != 0)
    327 		return error;
    328 
    329 	if (SCARG(uap, tp))
    330 		error = copyout(&ts, SCARG(uap, tp), sizeof(ts));
    331 
    332 	return error;
    333 }
    334 
    335 int
    336 clock_getres1(clockid_t clock_id, struct timespec *ts)
    337 {
    338 
    339 	switch (clock_id) {
    340 	case CLOCK_REALTIME:
    341 	case CLOCK_MONOTONIC:
    342 		ts->tv_sec = 0;
    343 		if (tc_getfrequency() > 1000000000)
    344 			ts->tv_nsec = 1;
    345 		else
    346 			ts->tv_nsec = 1000000000 / tc_getfrequency();
    347 		break;
    348 	default:
    349 		return EINVAL;
    350 	}
    351 
    352 	return 0;
    353 }
    354 
    355 /* ARGSUSED */
    356 int
    357 sys___nanosleep50(struct lwp *l, const struct sys___nanosleep50_args *uap,
    358     register_t *retval)
    359 {
    360 	/* {
    361 		syscallarg(struct timespec *) rqtp;
    362 		syscallarg(struct timespec *) rmtp;
    363 	} */
    364 	struct timespec rmt, rqt;
    365 	int error, error1;
    366 
    367 	error = copyin(SCARG(uap, rqtp), &rqt, sizeof(struct timespec));
    368 	if (error)
    369 		return error;
    370 
    371 	error = nanosleep1(l, CLOCK_MONOTONIC, 0, &rqt,
    372 	    SCARG(uap, rmtp) ? &rmt : NULL);
    373 	if (SCARG(uap, rmtp) == NULL || (error != 0 && error != EINTR))
    374 		return error;
    375 
    376 	error1 = copyout(&rmt, SCARG(uap, rmtp), sizeof(rmt));
    377 	return error1 ? error1 : error;
    378 }
    379 
    380 /* ARGSUSED */
    381 int
    382 sys_clock_nanosleep(struct lwp *l, const struct sys_clock_nanosleep_args *uap,
    383     register_t *retval)
    384 {
    385 	/* {
    386 		syscallarg(clockid_t) clock_id;
    387 		syscallarg(int) flags;
    388 		syscallarg(struct timespec *) rqtp;
    389 		syscallarg(struct timespec *) rmtp;
    390 	} */
    391 	struct timespec rmt, rqt;
    392 	int error, error1;
    393 
    394 	error = copyin(SCARG(uap, rqtp), &rqt, sizeof(struct timespec));
    395 	if (error)
    396 		goto out;
    397 
    398 	error = nanosleep1(l, SCARG(uap, clock_id), SCARG(uap, flags), &rqt,
    399 	    SCARG(uap, rmtp) ? &rmt : NULL);
    400 	if (SCARG(uap, rmtp) == NULL || (error != 0 && error != EINTR))
    401 		goto out;
    402 
    403 	if ((SCARG(uap, flags) & TIMER_ABSTIME) == 0 &&
    404 	    (error1 = copyout(&rmt, SCARG(uap, rmtp), sizeof(rmt))) != 0)
    405 		error = error1;
    406 out:
    407 	*retval = error;
    408 	return 0;
    409 }
    410 
    411 int
    412 nanosleep1(struct lwp *l, clockid_t clock_id, int flags, struct timespec *rqt,
    413     struct timespec *rmt)
    414 {
    415 	struct timespec rmtstart;
    416 	int error, timo;
    417 
    418 	if ((error = ts2timo(clock_id, flags, rqt, &timo, &rmtstart)) != 0) {
    419 		if (error == ETIMEDOUT) {
    420 			error = 0;
    421 			if (rmt != NULL)
    422 				rmt->tv_sec = rmt->tv_nsec = 0;
    423 		}
    424 		return error;
    425 	}
    426 
    427 	/*
    428 	 * Avoid inadvertently sleeping forever
    429 	 */
    430 	if (timo == 0)
    431 		timo = 1;
    432 again:
    433 	error = kpause("nanoslp", true, timo, NULL);
    434 	if (error == EWOULDBLOCK)
    435 		error = 0;
    436 	if (rmt != NULL || error == 0) {
    437 		struct timespec rmtend;
    438 		struct timespec t0;
    439 		struct timespec *t;
    440 		int err;
    441 
    442 		err = clock_gettime1(clock_id, &rmtend);
    443 		if (err != 0)
    444 			return err;
    445 
    446 		t = (rmt != NULL) ? rmt : &t0;
    447 		if (flags & TIMER_ABSTIME) {
    448 			timespecsub(rqt, &rmtend, t);
    449 		} else {
    450 			if (timespeccmp(&rmtend, &rmtstart, <))
    451 				timespecclear(t); /* clock wound back */
    452 			else
    453 				timespecsub(&rmtend, &rmtstart, t);
    454 			if (timespeccmp(rqt, t, <))
    455 				timespecclear(t);
    456 			else
    457 				timespecsub(rqt, t, t);
    458 		}
    459 		if (t->tv_sec < 0)
    460 			timespecclear(t);
    461 		if (error == 0) {
    462 			timo = tstohz(t);
    463 			if (timo > 0)
    464 				goto again;
    465 		}
    466 	}
    467 
    468 	if (error == ERESTART)
    469 		error = EINTR;
    470 
    471 	return error;
    472 }
    473 
    474 int
    475 sys_clock_getcpuclockid2(struct lwp *l,
    476     const struct sys_clock_getcpuclockid2_args *uap,
    477     register_t *retval)
    478 {
    479 	/* {
    480 		syscallarg(idtype_t idtype;
    481 		syscallarg(id_t id);
    482 		syscallarg(clockid_t *)clock_id;
    483 	} */
    484 	pid_t pid;
    485 	lwpid_t lid;
    486 	clockid_t clock_id;
    487 	id_t id = SCARG(uap, id);
    488 
    489 	switch (SCARG(uap, idtype)) {
    490 	case P_PID:
    491 		pid = id == 0 ? l->l_proc->p_pid : id;
    492 		clock_id = CLOCK_PROCESS_CPUTIME_ID | pid;
    493 		break;
    494 	case P_LWPID:
    495 		lid = id == 0 ? l->l_lid : id;
    496 		clock_id = CLOCK_THREAD_CPUTIME_ID | lid;
    497 		break;
    498 	default:
    499 		return EINVAL;
    500 	}
    501 	return copyout(&clock_id, SCARG(uap, clock_id), sizeof(clock_id));
    502 }
    503 
    504 /* ARGSUSED */
    505 int
    506 sys___gettimeofday50(struct lwp *l, const struct sys___gettimeofday50_args *uap,
    507     register_t *retval)
    508 {
    509 	/* {
    510 		syscallarg(struct timeval *) tp;
    511 		syscallarg(void *) tzp;		really "struct timezone *";
    512 	} */
    513 	struct timeval atv;
    514 	int error = 0;
    515 	struct timezone tzfake;
    516 
    517 	if (SCARG(uap, tp)) {
    518 		memset(&atv, 0, sizeof(atv));
    519 		microtime(&atv);
    520 		error = copyout(&atv, SCARG(uap, tp), sizeof(atv));
    521 		if (error)
    522 			return error;
    523 	}
    524 	if (SCARG(uap, tzp)) {
    525 		/*
    526 		 * NetBSD has no kernel notion of time zone, so we just
    527 		 * fake up a timezone struct and return it if demanded.
    528 		 */
    529 		tzfake.tz_minuteswest = 0;
    530 		tzfake.tz_dsttime = 0;
    531 		error = copyout(&tzfake, SCARG(uap, tzp), sizeof(tzfake));
    532 	}
    533 	return error;
    534 }
    535 
    536 /* ARGSUSED */
    537 int
    538 sys___settimeofday50(struct lwp *l, const struct sys___settimeofday50_args *uap,
    539     register_t *retval)
    540 {
    541 	/* {
    542 		syscallarg(const struct timeval *) tv;
    543 		syscallarg(const void *) tzp; really "const struct timezone *";
    544 	} */
    545 
    546 	return settimeofday1(SCARG(uap, tv), true, SCARG(uap, tzp), l, true);
    547 }
    548 
    549 int
    550 settimeofday1(const struct timeval *utv, bool userspace,
    551     const void *utzp, struct lwp *l, bool check_kauth)
    552 {
    553 	struct timeval atv;
    554 	struct timespec ts;
    555 	int error;
    556 
    557 	/* Verify all parameters before changing time. */
    558 
    559 	/*
    560 	 * NetBSD has no kernel notion of time zone, and only an
    561 	 * obsolete program would try to set it, so we log a warning.
    562 	 */
    563 	if (utzp)
    564 		log(LOG_WARNING, "pid %d attempted to set the "
    565 		    "(obsolete) kernel time zone\n", l->l_proc->p_pid);
    566 
    567 	if (utv == NULL)
    568 		return 0;
    569 
    570 	if (userspace) {
    571 		if ((error = copyin(utv, &atv, sizeof(atv))) != 0)
    572 			return error;
    573 		utv = &atv;
    574 	}
    575 
    576 	if (utv->tv_usec < 0 || utv->tv_usec >= 1000000)
    577 		return EINVAL;
    578 
    579 	TIMEVAL_TO_TIMESPEC(utv, &ts);
    580 	return settime1(l->l_proc, &ts, check_kauth);
    581 }
    582 
    583 int	time_adjusted;			/* set if an adjustment is made */
    584 
    585 /* ARGSUSED */
    586 int
    587 sys___adjtime50(struct lwp *l, const struct sys___adjtime50_args *uap,
    588     register_t *retval)
    589 {
    590 	/* {
    591 		syscallarg(const struct timeval *) delta;
    592 		syscallarg(struct timeval *) olddelta;
    593 	} */
    594 	int error;
    595 	struct timeval atv, oldatv;
    596 
    597 	if ((error = kauth_authorize_system(l->l_cred, KAUTH_SYSTEM_TIME,
    598 	    KAUTH_REQ_SYSTEM_TIME_ADJTIME, NULL, NULL, NULL)) != 0)
    599 		return error;
    600 
    601 	if (SCARG(uap, delta)) {
    602 		error = copyin(SCARG(uap, delta), &atv,
    603 		    sizeof(*SCARG(uap, delta)));
    604 		if (error)
    605 			return error;
    606 	}
    607 	adjtime1(SCARG(uap, delta) ? &atv : NULL,
    608 	    SCARG(uap, olddelta) ? &oldatv : NULL, l->l_proc);
    609 	if (SCARG(uap, olddelta))
    610 		error = copyout(&oldatv, SCARG(uap, olddelta),
    611 		    sizeof(*SCARG(uap, olddelta)));
    612 	return error;
    613 }
    614 
    615 void
    616 adjtime1(const struct timeval *delta, struct timeval *olddelta, struct proc *p)
    617 {
    618 
    619 	if (olddelta) {
    620 		memset(olddelta, 0, sizeof(*olddelta));
    621 		mutex_spin_enter(&timecounter_lock);
    622 		olddelta->tv_sec = time_adjtime / 1000000;
    623 		olddelta->tv_usec = time_adjtime % 1000000;
    624 		if (olddelta->tv_usec < 0) {
    625 			olddelta->tv_usec += 1000000;
    626 			olddelta->tv_sec--;
    627 		}
    628 		mutex_spin_exit(&timecounter_lock);
    629 	}
    630 
    631 	if (delta) {
    632 		mutex_spin_enter(&timecounter_lock);
    633 		/*
    634 		 * XXX This should maybe just report failure to
    635 		 * userland for nonsense deltas.
    636 		 */
    637 		if (delta->tv_sec > INT64_MAX/1000000 - 1) {
    638 			time_adjtime = INT64_MAX;
    639 		} else if (delta->tv_sec < INT64_MIN/1000000 + 1) {
    640 			time_adjtime = INT64_MIN;
    641 		} else {
    642 			time_adjtime = delta->tv_sec * 1000000
    643 			    + MAX(-999999, MIN(999999, delta->tv_usec));
    644 		}
    645 
    646 		if (time_adjtime) {
    647 			/* We need to save the system time during shutdown */
    648 			time_adjusted |= 1;
    649 		}
    650 		mutex_spin_exit(&timecounter_lock);
    651 	}
    652 }
    653 
    654 /*
    655  * Interval timer support.
    656  *
    657  * The itimer_*() routines provide generic support for interval timers,
    658  * both real (CLOCK_REALTIME, CLOCK_MONOTIME), and virtual (CLOCK_VIRTUAL,
    659  * CLOCK_PROF).
    660  *
    661  * Real timers keep their deadline as an absolute time, and are fired
    662  * by a callout.  Virtual timers are kept as a linked-list of deltas,
    663  * and are processed by hardclock().
    664  *
    665  * Because the real time timer callout may be delayed in real time due
    666  * to interrupt processing on the system, it is possible for the real
    667  * time timeout routine (itimer_callout()) run past after its deadline.
    668  * It does not suffice, therefore, to reload the real timer .it_value
    669  * from the timer's .it_interval.  Rather, we compute the next deadline
    670  * in absolute time based on the current time and the .it_interval value,
    671  * and report any overruns.
    672  *
    673  * Note that while the virtual timers are supported in a generic fashion
    674  * here, they only (currently) make sense as per-process timers, and thus
    675  * only really work for that case.
    676  */
    677 
    678 /*
    679  * itimer_init:
    680  *
    681  *	Initialize the common data for an interval timer.
    682  */
    683 void
    684 itimer_init(struct itimer * const it, const struct itimer_ops * const ops,
    685     clockid_t const id, struct itlist * const itl)
    686 {
    687 
    688 	KASSERT(itimer_lock_held());
    689 	KASSERT(ops != NULL);
    690 
    691 	timespecclear(&it->it_time.it_value);
    692 	it->it_ops = ops;
    693 	it->it_clockid = id;
    694 	it->it_overruns = 0;
    695 	it->it_dying = false;
    696 	if (!CLOCK_VIRTUAL_P(id)) {
    697 		KASSERT(itl == NULL);
    698 		callout_init(&it->it_ch, CALLOUT_MPSAFE);
    699 		callout_setfunc(&it->it_ch, itimer_callout, it);
    700 		if (id == CLOCK_REALTIME && ops->ito_realtime_changed != NULL) {
    701 			LIST_INSERT_HEAD(&itimer_realtime_changed_notify,
    702 			    it, it_rtchgq);
    703 		}
    704 	} else {
    705 		KASSERT(itl != NULL);
    706 		it->it_vlist = itl;
    707 		it->it_active = false;
    708 	}
    709 }
    710 
    711 /*
    712  * itimer_poison:
    713  *
    714  *	Poison an interval timer, preventing it from being scheduled
    715  *	or processed, in preparation for freeing the timer.
    716  */
    717 void
    718 itimer_poison(struct itimer * const it)
    719 {
    720 
    721 	KASSERT(itimer_lock_held());
    722 
    723 	it->it_dying = true;
    724 
    725 	/*
    726 	 * For non-virtual timers, stop the callout, or wait for it to
    727 	 * run if it has already fired.  It cannot restart again after
    728 	 * this point: the callout won't restart itself when dying, no
    729 	 * other users holding the lock can restart it, and any other
    730 	 * users waiting for callout_halt concurrently (itimer_settime)
    731 	 * will restart from the top.
    732 	 */
    733 	if (!CLOCK_VIRTUAL_P(it->it_clockid)) {
    734 		callout_halt(&it->it_ch, &itimer_mutex);
    735 		if (it->it_clockid == CLOCK_REALTIME &&
    736 		    it->it_ops->ito_realtime_changed != NULL) {
    737 			LIST_REMOVE(it, it_rtchgq);
    738 		}
    739 	}
    740 }
    741 
    742 /*
    743  * itimer_fini:
    744  *
    745  *	Release resources used by an interval timer.
    746  *
    747  *	N.B. itimer_lock must be held on entry, and is released on exit.
    748  */
    749 void
    750 itimer_fini(struct itimer * const it)
    751 {
    752 
    753 	KASSERT(itimer_lock_held());
    754 
    755 	/* All done with the global state. */
    756 	itimer_unlock();
    757 
    758 	/* Destroy the callout, if needed. */
    759 	if (!CLOCK_VIRTUAL_P(it->it_clockid))
    760 		callout_destroy(&it->it_ch);
    761 }
    762 
    763 /*
    764  * itimer_decr:
    765  *
    766  *	Decrement an interval timer by a specified number of nanoseconds,
    767  *	which must be less than a second, i.e. < 1000000000.  If the timer
    768  *	expires, then reload it.  In this case, carry over (nsec - old value)
    769  *	to reduce the value reloaded into the timer so that the timer does
    770  *	not drift.  This routine assumes that it is called in a context where
    771  *	the timers on which it is operating cannot change in value.
    772  *
    773  *	Returns true if the timer has expired.
    774  */
    775 static bool
    776 itimer_decr(struct itimer *it, int nsec)
    777 {
    778 	struct itimerspec *itp;
    779 	int error __diagused;
    780 
    781 	KASSERT(itimer_lock_held());
    782 	KASSERT(CLOCK_VIRTUAL_P(it->it_clockid));
    783 
    784 	itp = &it->it_time;
    785 	if (itp->it_value.tv_nsec < nsec) {
    786 		if (itp->it_value.tv_sec == 0) {
    787 			/* expired, and already in next interval */
    788 			nsec -= itp->it_value.tv_nsec;
    789 			goto expire;
    790 		}
    791 		itp->it_value.tv_nsec += 1000000000;
    792 		itp->it_value.tv_sec--;
    793 	}
    794 	itp->it_value.tv_nsec -= nsec;
    795 	nsec = 0;
    796 	if (timespecisset(&itp->it_value))
    797 		return false;
    798 	/* expired, exactly at end of interval */
    799  expire:
    800 	if (timespecisset(&itp->it_interval)) {
    801 		itp->it_value = itp->it_interval;
    802 		itp->it_value.tv_nsec -= nsec;
    803 		if (itp->it_value.tv_nsec < 0) {
    804 			itp->it_value.tv_nsec += 1000000000;
    805 			itp->it_value.tv_sec--;
    806 		}
    807 		error = itimer_settime(it);
    808 		KASSERT(error == 0); /* virtual, never fails */
    809 	} else
    810 		itp->it_value.tv_nsec = 0;		/* sec is already 0 */
    811 	return true;
    812 }
    813 
    814 /*
    815  * itimer_arm_real:
    816  *
    817  *	Arm a non-virtual timer.
    818  */
    819 static void
    820 itimer_arm_real(struct itimer * const it)
    821 {
    822 
    823 	KASSERT(!it->it_dying);
    824 	KASSERT(!CLOCK_VIRTUAL_P(it->it_clockid));
    825 	KASSERT(!callout_pending(&it->it_ch));
    826 
    827 	/*
    828 	 * Don't need to check tshzto() return value, here.
    829 	 * callout_schedule() does it for us.
    830 	 */
    831 	callout_schedule(&it->it_ch,
    832 	    (it->it_clockid == CLOCK_MONOTONIC
    833 		? tshztoup(&it->it_time.it_value)
    834 		: tshzto(&it->it_time.it_value)));
    835 }
    836 
    837 /*
    838  * itimer_callout:
    839  *
    840  *	Callout to expire a non-virtual timer.  Queue it up for processing,
    841  *	and then reload, if it is configured to do so.
    842  *
    843  *	N.B. A delay in processing this callout causes multiple
    844  *	SIGALRM calls to be compressed into one.
    845  */
    846 static void
    847 itimer_callout(void *arg)
    848 {
    849 	uint64_t last_val, next_val, interval, now_ns;
    850 	struct timespec now, next;
    851 	struct itimer * const it = arg;
    852 	int backwards;
    853 
    854 	itimer_lock();
    855 	(*it->it_ops->ito_fire)(it);
    856 
    857 	if (!timespecisset(&it->it_time.it_interval)) {
    858 		timespecclear(&it->it_time.it_value);
    859 		itimer_unlock();
    860 		return;
    861 	}
    862 
    863 	if (it->it_clockid == CLOCK_MONOTONIC) {
    864 		getnanouptime(&now);
    865 	} else {
    866 		getnanotime(&now);
    867 	}
    868 
    869 	backwards = (timespeccmp(&it->it_time.it_value, &now, >));
    870 
    871 	/* Nonnegative interval guaranteed by itimerfix.  */
    872 	KASSERT(it->it_time.it_interval.tv_sec >= 0);
    873 	KASSERT(it->it_time.it_interval.tv_nsec >= 0);
    874 
    875 	/* Handle the easy case of non-overflown timers first. */
    876 	if (!backwards &&
    877 	    timespecaddok(&it->it_time.it_value, &it->it_time.it_interval)) {
    878 		timespecadd(&it->it_time.it_value, &it->it_time.it_interval,
    879 		    &next);
    880 		it->it_time.it_value = next;
    881 	} else {
    882 		now_ns = timespec2ns(&now);
    883 		last_val = timespec2ns(&it->it_time.it_value);
    884 		interval = timespec2ns(&it->it_time.it_interval);
    885 
    886 		next_val = now_ns +
    887 		    (now_ns - last_val + interval - 1) % interval;
    888 
    889 		if (backwards)
    890 			next_val += interval;
    891 		else
    892 			it->it_overruns += (now_ns - last_val) / interval;
    893 
    894 		it->it_time.it_value.tv_sec = next_val / 1000000000;
    895 		it->it_time.it_value.tv_nsec = next_val % 1000000000;
    896 	}
    897 
    898 	/*
    899 	 * Reset the callout, if it's not going away.
    900 	 */
    901 	if (!it->it_dying)
    902 		itimer_arm_real(it);
    903 	itimer_unlock();
    904 }
    905 
    906 /*
    907  * itimer_settime:
    908  *
    909  *	Set up the given interval timer. The value in it->it_time.it_value
    910  *	is taken to be an absolute time for CLOCK_REALTIME/CLOCK_MONOTONIC
    911  *	timers and a relative time for CLOCK_VIRTUAL/CLOCK_PROF timers.
    912  *
    913  *	If the callout had already fired but not yet run, fails with
    914  *	ERESTART -- caller must restart from the top to look up a timer.
    915  *
    916  *	Caller is responsible for validating it->it_value and
    917  *	it->it_interval, e.g. with itimerfix or itimespecfix.
    918  */
    919 int
    920 itimer_settime(struct itimer *it)
    921 {
    922 	struct itimer *itn, *pitn;
    923 	struct itlist *itl;
    924 
    925 	KASSERT(itimer_lock_held());
    926 	KASSERT(!it->it_dying);
    927 	KASSERT(it->it_time.it_value.tv_sec >= 0);
    928 	KASSERT(it->it_time.it_value.tv_nsec >= 0);
    929 	KASSERT(it->it_time.it_value.tv_nsec < 1000000000);
    930 	KASSERT(it->it_time.it_interval.tv_sec >= 0);
    931 	KASSERT(it->it_time.it_interval.tv_nsec >= 0);
    932 	KASSERT(it->it_time.it_interval.tv_nsec < 1000000000);
    933 
    934 	if (!CLOCK_VIRTUAL_P(it->it_clockid)) {
    935 		/*
    936 		 * Try to stop the callout.  However, if it had already
    937 		 * fired, we have to drop the lock to wait for it, so
    938 		 * the world may have changed and pt may not be there
    939 		 * any more.  In that case, tell the caller to start
    940 		 * over from the top.
    941 		 */
    942 		if (callout_halt(&it->it_ch, &itimer_mutex))
    943 			return ERESTART;
    944 		KASSERT(!it->it_dying);
    945 
    946 		/* Now we can touch it and start it up again. */
    947 		if (timespecisset(&it->it_time.it_value))
    948 			itimer_arm_real(it);
    949 	} else {
    950 		if (it->it_active) {
    951 			itn = LIST_NEXT(it, it_list);
    952 			LIST_REMOVE(it, it_list);
    953 			for ( ; itn; itn = LIST_NEXT(itn, it_list))
    954 				timespecadd(&it->it_time.it_value,
    955 				    &itn->it_time.it_value,
    956 				    &itn->it_time.it_value);
    957 		}
    958 		if (timespecisset(&it->it_time.it_value)) {
    959 			itl = it->it_vlist;
    960 			for (itn = LIST_FIRST(itl), pitn = NULL;
    961 			     itn && timespeccmp(&it->it_time.it_value,
    962 				 &itn->it_time.it_value, >);
    963 			     pitn = itn, itn = LIST_NEXT(itn, it_list))
    964 				timespecsub(&it->it_time.it_value,
    965 				    &itn->it_time.it_value,
    966 				    &it->it_time.it_value);
    967 
    968 			if (pitn)
    969 				LIST_INSERT_AFTER(pitn, it, it_list);
    970 			else
    971 				LIST_INSERT_HEAD(itl, it, it_list);
    972 
    973 			for ( ; itn ; itn = LIST_NEXT(itn, it_list))
    974 				timespecsub(&itn->it_time.it_value,
    975 				    &it->it_time.it_value,
    976 				    &itn->it_time.it_value);
    977 
    978 			it->it_active = true;
    979 		} else {
    980 			it->it_active = false;
    981 		}
    982 	}
    983 
    984 	/* Success!  */
    985 	return 0;
    986 }
    987 
    988 /*
    989  * itimer_gettime:
    990  *
    991  *	Return the remaining time of an interval timer.
    992  */
    993 void
    994 itimer_gettime(const struct itimer *it, struct itimerspec *aits)
    995 {
    996 	struct timespec now;
    997 	struct itimer *itn;
    998 
    999 	KASSERT(itimer_lock_held());
   1000 	KASSERT(!it->it_dying);
   1001 
   1002 	*aits = it->it_time;
   1003 	if (!CLOCK_VIRTUAL_P(it->it_clockid)) {
   1004 		/*
   1005 		 * Convert from absolute to relative time in .it_value
   1006 		 * part of real time timer.  If time for real time
   1007 		 * timer has passed return 0, else return difference
   1008 		 * between current time and time for the timer to go
   1009 		 * off.
   1010 		 */
   1011 		if (timespecisset(&aits->it_value)) {
   1012 			if (it->it_clockid == CLOCK_REALTIME) {
   1013 				getnanotime(&now);
   1014 			} else { /* CLOCK_MONOTONIC */
   1015 				getnanouptime(&now);
   1016 			}
   1017 			if (timespeccmp(&aits->it_value, &now, <))
   1018 				timespecclear(&aits->it_value);
   1019 			else
   1020 				timespecsub(&aits->it_value, &now,
   1021 				    &aits->it_value);
   1022 		}
   1023 	} else if (it->it_active) {
   1024 		for (itn = LIST_FIRST(it->it_vlist); itn && itn != it;
   1025 		     itn = LIST_NEXT(itn, it_list))
   1026 			timespecadd(&aits->it_value,
   1027 			    &itn->it_time.it_value, &aits->it_value);
   1028 		KASSERT(itn != NULL); /* it should be findable on the list */
   1029 	} else
   1030 		timespecclear(&aits->it_value);
   1031 }
   1032 
   1033 /*
   1034  * Per-process timer support.
   1035  *
   1036  * Both the BSD getitimer() family and the POSIX timer_*() family of
   1037  * routines are supported.
   1038  *
   1039  * All timers are kept in an array pointed to by p_timers, which is
   1040  * allocated on demand - many processes don't use timers at all. The
   1041  * first four elements in this array are reserved for the BSD timers:
   1042  * element 0 is ITIMER_REAL, element 1 is ITIMER_VIRTUAL, element
   1043  * 2 is ITIMER_PROF, and element 3 is ITIMER_MONOTONIC. The rest may be
   1044  * allocated by the timer_create() syscall.
   1045  *
   1046  * These timers are a "sub-class" of interval timer.
   1047  */
   1048 
   1049 /*
   1050  * ptimer_free:
   1051  *
   1052  *	Free the per-process timer at the specified index.
   1053  */
   1054 static void
   1055 ptimer_free(struct ptimers *pts, int index)
   1056 {
   1057 	struct itimer *it;
   1058 	struct ptimer *pt;
   1059 
   1060 	KASSERT(itimer_lock_held());
   1061 
   1062 	it = pts->pts_timers[index];
   1063 	pt = container_of(it, struct ptimer, pt_itimer);
   1064 	pts->pts_timers[index] = NULL;
   1065 	itimer_poison(it);
   1066 
   1067 	/*
   1068 	 * Remove it from the queue to be signalled.  Must be done
   1069 	 * after itimer is poisoned, because we may have had to wait
   1070 	 * for the callout to complete.
   1071 	 */
   1072 	if (pt->pt_queued) {
   1073 		TAILQ_REMOVE(&ptimer_queue, pt, pt_chain);
   1074 		pt->pt_queued = false;
   1075 	}
   1076 
   1077 	itimer_fini(it);	/* releases itimer_lock */
   1078 	kmem_free(pt, sizeof(*pt));
   1079 }
   1080 
   1081 /*
   1082  * ptimers_alloc:
   1083  *
   1084  *	Allocate a ptimers for the specified process.
   1085  */
   1086 static struct ptimers *
   1087 ptimers_alloc(struct proc *p)
   1088 {
   1089 	struct ptimers *pts;
   1090 	int i;
   1091 
   1092 	pts = kmem_alloc(sizeof(*pts), KM_SLEEP);
   1093 	LIST_INIT(&pts->pts_virtual);
   1094 	LIST_INIT(&pts->pts_prof);
   1095 	for (i = 0; i < TIMER_MAX; i++)
   1096 		pts->pts_timers[i] = NULL;
   1097 	itimer_lock();
   1098 	if (p->p_timers == NULL) {
   1099 		p->p_timers = pts;
   1100 		itimer_unlock();
   1101 		return pts;
   1102 	}
   1103 	itimer_unlock();
   1104 	kmem_free(pts, sizeof(*pts));
   1105 	return p->p_timers;
   1106 }
   1107 
   1108 /*
   1109  * ptimers_free:
   1110  *
   1111  *	Clean up the per-process timers. If "which" is set to TIMERS_ALL,
   1112  *	then clean up all timers and free all the data structures. If
   1113  *	"which" is set to TIMERS_POSIX, only clean up the timers allocated
   1114  *	by timer_create(), not the BSD setitimer() timers, and only free the
   1115  *	structure if none of those remain.
   1116  *
   1117  *	This function is exported because it is needed in the exec and
   1118  *	exit code paths.
   1119  */
   1120 void
   1121 ptimers_free(struct proc *p, int which)
   1122 {
   1123 	struct ptimers *pts;
   1124 	struct itimer *itn;
   1125 	struct timespec ts;
   1126 	int i;
   1127 
   1128 	if (p->p_timers == NULL)
   1129 		return;
   1130 
   1131 	pts = p->p_timers;
   1132 	itimer_lock();
   1133 	if (which == TIMERS_ALL) {
   1134 		p->p_timers = NULL;
   1135 		i = 0;
   1136 	} else {
   1137 		timespecclear(&ts);
   1138 		for (itn = LIST_FIRST(&pts->pts_virtual);
   1139 		     itn && itn != pts->pts_timers[ITIMER_VIRTUAL];
   1140 		     itn = LIST_NEXT(itn, it_list)) {
   1141 			KASSERT(itn->it_clockid == CLOCK_VIRTUAL);
   1142 			timespecadd(&ts, &itn->it_time.it_value, &ts);
   1143 		}
   1144 		LIST_FIRST(&pts->pts_virtual) = NULL;
   1145 		if (itn) {
   1146 			KASSERT(itn->it_clockid == CLOCK_VIRTUAL);
   1147 			timespecadd(&ts, &itn->it_time.it_value,
   1148 			    &itn->it_time.it_value);
   1149 			LIST_INSERT_HEAD(&pts->pts_virtual, itn, it_list);
   1150 		}
   1151 		timespecclear(&ts);
   1152 		for (itn = LIST_FIRST(&pts->pts_prof);
   1153 		     itn && itn != pts->pts_timers[ITIMER_PROF];
   1154 		     itn = LIST_NEXT(itn, it_list)) {
   1155 			KASSERT(itn->it_clockid == CLOCK_PROF);
   1156 			timespecadd(&ts, &itn->it_time.it_value, &ts);
   1157 		}
   1158 		LIST_FIRST(&pts->pts_prof) = NULL;
   1159 		if (itn) {
   1160 			KASSERT(itn->it_clockid == CLOCK_PROF);
   1161 			timespecadd(&ts, &itn->it_time.it_value,
   1162 			    &itn->it_time.it_value);
   1163 			LIST_INSERT_HEAD(&pts->pts_prof, itn, it_list);
   1164 		}
   1165 		i = TIMER_MIN;
   1166 	}
   1167 	for ( ; i < TIMER_MAX; i++) {
   1168 		if (pts->pts_timers[i] != NULL) {
   1169 			/* Free the timer and release the lock.  */
   1170 			ptimer_free(pts, i);
   1171 			/* Reacquire the lock for the next one.  */
   1172 			itimer_lock();
   1173 		}
   1174 	}
   1175 	if (pts->pts_timers[0] == NULL && pts->pts_timers[1] == NULL &&
   1176 	    pts->pts_timers[2] == NULL && pts->pts_timers[3] == NULL) {
   1177 		p->p_timers = NULL;
   1178 		itimer_unlock();
   1179 		kmem_free(pts, sizeof(*pts));
   1180 	} else
   1181 		itimer_unlock();
   1182 }
   1183 
   1184 /*
   1185  * ptimer_fire:
   1186  *
   1187  *	Fire a per-process timer.
   1188  */
   1189 static void
   1190 ptimer_fire(struct itimer *it)
   1191 {
   1192 	struct ptimer *pt = container_of(it, struct ptimer, pt_itimer);
   1193 
   1194 	KASSERT(itimer_lock_held());
   1195 
   1196 	/*
   1197 	 * XXX Can overrun, but we don't do signal queueing yet, anyway.
   1198 	 * XXX Relying on the clock interrupt is stupid.
   1199 	 */
   1200 	if (pt->pt_ev.sigev_notify != SIGEV_SIGNAL) {
   1201 		return;
   1202 	}
   1203 
   1204 	if (!pt->pt_queued) {
   1205 		TAILQ_INSERT_TAIL(&ptimer_queue, pt, pt_chain);
   1206 		pt->pt_queued = true;
   1207 		softint_schedule(ptimer_sih);
   1208 	}
   1209 }
   1210 
   1211 /*
   1212  * Operations vector for per-process timers (BSD and POSIX).
   1213  */
   1214 static const struct itimer_ops ptimer_itimer_ops = {
   1215 	.ito_fire = ptimer_fire,
   1216 };
   1217 
   1218 /*
   1219  * sys_timer_create:
   1220  *
   1221  *	System call to create a POSIX timer.
   1222  */
   1223 int
   1224 sys_timer_create(struct lwp *l, const struct sys_timer_create_args *uap,
   1225     register_t *retval)
   1226 {
   1227 	/* {
   1228 		syscallarg(clockid_t) clock_id;
   1229 		syscallarg(struct sigevent *) evp;
   1230 		syscallarg(timer_t *) timerid;
   1231 	} */
   1232 
   1233 	return timer_create1(SCARG(uap, timerid), SCARG(uap, clock_id),
   1234 	    SCARG(uap, evp), copyin, l);
   1235 }
   1236 
   1237 int
   1238 timer_create1(timer_t *tid, clockid_t id, struct sigevent *evp,
   1239     copyin_t fetch_event, struct lwp *l)
   1240 {
   1241 	int error;
   1242 	timer_t timerid;
   1243 	struct itlist *itl;
   1244 	struct ptimers *pts;
   1245 	struct ptimer *pt;
   1246 	struct proc *p;
   1247 
   1248 	p = l->l_proc;
   1249 
   1250 	if ((u_int)id > CLOCK_MONOTONIC)
   1251 		return EINVAL;
   1252 
   1253 	if ((pts = p->p_timers) == NULL)
   1254 		pts = ptimers_alloc(p);
   1255 
   1256 	pt = kmem_zalloc(sizeof(*pt), KM_SLEEP);
   1257 	if (evp != NULL) {
   1258 		if (((error =
   1259 		    (*fetch_event)(evp, &pt->pt_ev, sizeof(pt->pt_ev))) != 0) ||
   1260 		    ((pt->pt_ev.sigev_notify < SIGEV_NONE) ||
   1261 			(pt->pt_ev.sigev_notify > SIGEV_SA)) ||
   1262 			(pt->pt_ev.sigev_notify == SIGEV_SIGNAL &&
   1263 			 (pt->pt_ev.sigev_signo <= 0 ||
   1264 			  pt->pt_ev.sigev_signo >= NSIG))) {
   1265 			kmem_free(pt, sizeof(*pt));
   1266 			return (error ? error : EINVAL);
   1267 		}
   1268 	}
   1269 
   1270 	/* Find a free timer slot, skipping those reserved for setitimer(). */
   1271 	itimer_lock();
   1272 	for (timerid = TIMER_MIN; timerid < TIMER_MAX; timerid++)
   1273 		if (pts->pts_timers[timerid] == NULL)
   1274 			break;
   1275 	if (timerid == TIMER_MAX) {
   1276 		itimer_unlock();
   1277 		kmem_free(pt, sizeof(*pt));
   1278 		return EAGAIN;
   1279 	}
   1280 	if (evp == NULL) {
   1281 		pt->pt_ev.sigev_notify = SIGEV_SIGNAL;
   1282 		switch (id) {
   1283 		case CLOCK_REALTIME:
   1284 		case CLOCK_MONOTONIC:
   1285 			pt->pt_ev.sigev_signo = SIGALRM;
   1286 			break;
   1287 		case CLOCK_VIRTUAL:
   1288 			pt->pt_ev.sigev_signo = SIGVTALRM;
   1289 			break;
   1290 		case CLOCK_PROF:
   1291 			pt->pt_ev.sigev_signo = SIGPROF;
   1292 			break;
   1293 		}
   1294 		pt->pt_ev.sigev_value.sival_int = timerid;
   1295 	}
   1296 
   1297 	switch (id) {
   1298 	case CLOCK_VIRTUAL:
   1299 		itl = &pts->pts_virtual;
   1300 		break;
   1301 	case CLOCK_PROF:
   1302 		itl = &pts->pts_prof;
   1303 		break;
   1304 	default:
   1305 		itl = NULL;
   1306 	}
   1307 
   1308 	itimer_init(&pt->pt_itimer, &ptimer_itimer_ops, id, itl);
   1309 	pt->pt_proc = p;
   1310 	pt->pt_poverruns = 0;
   1311 	pt->pt_entry = timerid;
   1312 	pt->pt_queued = false;
   1313 
   1314 	pts->pts_timers[timerid] = &pt->pt_itimer;
   1315 	itimer_unlock();
   1316 
   1317 	return copyout(&timerid, tid, sizeof(timerid));
   1318 }
   1319 
   1320 /*
   1321  * sys_timer_delete:
   1322  *
   1323  *	System call to delete a POSIX timer.
   1324  */
   1325 int
   1326 sys_timer_delete(struct lwp *l, const struct sys_timer_delete_args *uap,
   1327     register_t *retval)
   1328 {
   1329 	/* {
   1330 		syscallarg(timer_t) timerid;
   1331 	} */
   1332 	struct proc *p = l->l_proc;
   1333 	timer_t timerid;
   1334 	struct ptimers *pts;
   1335 	struct itimer *it, *itn;
   1336 
   1337 	timerid = SCARG(uap, timerid);
   1338 	pts = p->p_timers;
   1339 
   1340 	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
   1341 		return EINVAL;
   1342 
   1343 	itimer_lock();
   1344 	if ((it = pts->pts_timers[timerid]) == NULL) {
   1345 		itimer_unlock();
   1346 		return EINVAL;
   1347 	}
   1348 
   1349 	if (CLOCK_VIRTUAL_P(it->it_clockid)) {
   1350 		if (it->it_active) {
   1351 			itn = LIST_NEXT(it, it_list);
   1352 			LIST_REMOVE(it, it_list);
   1353 			for ( ; itn; itn = LIST_NEXT(itn, it_list))
   1354 				timespecadd(&it->it_time.it_value,
   1355 				    &itn->it_time.it_value,
   1356 				    &itn->it_time.it_value);
   1357 			it->it_active = false;
   1358 		}
   1359 	}
   1360 
   1361 	/* Free the timer and release the lock.  */
   1362 	ptimer_free(pts, timerid);
   1363 
   1364 	return 0;
   1365 }
   1366 
   1367 /*
   1368  * sys___timer_settime50:
   1369  *
   1370  *	System call to set/arm a POSIX timer.
   1371  */
   1372 int
   1373 sys___timer_settime50(struct lwp *l,
   1374     const struct sys___timer_settime50_args *uap,
   1375     register_t *retval)
   1376 {
   1377 	/* {
   1378 		syscallarg(timer_t) timerid;
   1379 		syscallarg(int) flags;
   1380 		syscallarg(const struct itimerspec *) value;
   1381 		syscallarg(struct itimerspec *) ovalue;
   1382 	} */
   1383 	int error;
   1384 	struct itimerspec value, ovalue, *ovp = NULL;
   1385 
   1386 	if ((error = copyin(SCARG(uap, value), &value,
   1387 	    sizeof(struct itimerspec))) != 0)
   1388 		return error;
   1389 
   1390 	if (SCARG(uap, ovalue))
   1391 		ovp = &ovalue;
   1392 
   1393 	if ((error = dotimer_settime(SCARG(uap, timerid), &value, ovp,
   1394 	    SCARG(uap, flags), l->l_proc)) != 0)
   1395 		return error;
   1396 
   1397 	if (ovp)
   1398 		return copyout(&ovalue, SCARG(uap, ovalue),
   1399 		    sizeof(struct itimerspec));
   1400 	return 0;
   1401 }
   1402 
   1403 int
   1404 dotimer_settime(int timerid, struct itimerspec *value,
   1405     struct itimerspec *ovalue, int flags, struct proc *p)
   1406 {
   1407 	struct timespec now;
   1408 	struct itimerspec val;
   1409 	struct ptimers *pts;
   1410 	struct itimer *it;
   1411 	int error;
   1412 
   1413 	pts = p->p_timers;
   1414 
   1415 	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
   1416 		return EINVAL;
   1417 	val = *value;
   1418 	if (itimespecfix(&val.it_value) != 0 ||
   1419 	    itimespecfix(&val.it_interval) != 0)
   1420 		return EINVAL;
   1421 
   1422 	itimer_lock();
   1423  restart:
   1424 	if ((it = pts->pts_timers[timerid]) == NULL) {
   1425 		itimer_unlock();
   1426 		return EINVAL;
   1427 	}
   1428 
   1429 	if (ovalue)
   1430 		itimer_gettime(it, ovalue);
   1431 	it->it_time = val;
   1432 
   1433 	/*
   1434 	 * If we've been passed a relative time for a realtime timer,
   1435 	 * convert it to absolute; if an absolute time for a virtual
   1436 	 * timer, convert it to relative and make sure we don't set it
   1437 	 * to zero, which would cancel the timer, or let it go
   1438 	 * negative, which would confuse the comparison tests.
   1439 	 */
   1440 	if (timespecisset(&it->it_time.it_value)) {
   1441 		if (!CLOCK_VIRTUAL_P(it->it_clockid)) {
   1442 			if ((flags & TIMER_ABSTIME) == 0) {
   1443 				if (it->it_clockid == CLOCK_REALTIME) {
   1444 					getnanotime(&now);
   1445 				} else { /* CLOCK_MONOTONIC */
   1446 					getnanouptime(&now);
   1447 				}
   1448 				timespecadd(&it->it_time.it_value, &now,
   1449 				    &it->it_time.it_value);
   1450 			}
   1451 		} else {
   1452 			if ((flags & TIMER_ABSTIME) != 0) {
   1453 				getnanotime(&now);
   1454 				timespecsub(&it->it_time.it_value, &now,
   1455 				    &it->it_time.it_value);
   1456 				if (!timespecisset(&it->it_time.it_value) ||
   1457 				    it->it_time.it_value.tv_sec < 0) {
   1458 					it->it_time.it_value.tv_sec = 0;
   1459 					it->it_time.it_value.tv_nsec = 1;
   1460 				}
   1461 			}
   1462 		}
   1463 	}
   1464 
   1465 	error = itimer_settime(it);
   1466 	if (error == ERESTART) {
   1467 		KASSERT(!CLOCK_VIRTUAL_P(it->it_clockid));
   1468 		goto restart;
   1469 	}
   1470 	KASSERT(error == 0);
   1471 	itimer_unlock();
   1472 
   1473 	return 0;
   1474 }
   1475 
   1476 /*
   1477  * sys___timer_gettime50:
   1478  *
   1479  *	System call to return the time remaining until a POSIX timer fires.
   1480  */
   1481 int
   1482 sys___timer_gettime50(struct lwp *l,
   1483     const struct sys___timer_gettime50_args *uap, register_t *retval)
   1484 {
   1485 	/* {
   1486 		syscallarg(timer_t) timerid;
   1487 		syscallarg(struct itimerspec *) value;
   1488 	} */
   1489 	struct itimerspec its;
   1490 	int error;
   1491 
   1492 	if ((error = dotimer_gettime(SCARG(uap, timerid), l->l_proc,
   1493 	    &its)) != 0)
   1494 		return error;
   1495 
   1496 	return copyout(&its, SCARG(uap, value), sizeof(its));
   1497 }
   1498 
   1499 int
   1500 dotimer_gettime(int timerid, struct proc *p, struct itimerspec *its)
   1501 {
   1502 	struct itimer *it;
   1503 	struct ptimers *pts;
   1504 
   1505 	pts = p->p_timers;
   1506 	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
   1507 		return EINVAL;
   1508 	itimer_lock();
   1509 	if ((it = pts->pts_timers[timerid]) == NULL) {
   1510 		itimer_unlock();
   1511 		return EINVAL;
   1512 	}
   1513 	itimer_gettime(it, its);
   1514 	itimer_unlock();
   1515 
   1516 	return 0;
   1517 }
   1518 
   1519 /*
   1520  * sys_timer_getoverrun:
   1521  *
   1522  *	System call to return the number of times a POSIX timer has
   1523  *	expired while a notification was already pending.  The counter
   1524  *	is reset when a timer expires and a notification can be posted.
   1525  */
   1526 int
   1527 sys_timer_getoverrun(struct lwp *l, const struct sys_timer_getoverrun_args *uap,
   1528     register_t *retval)
   1529 {
   1530 	/* {
   1531 		syscallarg(timer_t) timerid;
   1532 	} */
   1533 	struct proc *p = l->l_proc;
   1534 	struct ptimers *pts;
   1535 	int timerid;
   1536 	struct itimer *it;
   1537 	struct ptimer *pt;
   1538 
   1539 	timerid = SCARG(uap, timerid);
   1540 
   1541 	pts = p->p_timers;
   1542 	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
   1543 		return EINVAL;
   1544 	itimer_lock();
   1545 	if ((it = pts->pts_timers[timerid]) == NULL) {
   1546 		itimer_unlock();
   1547 		return EINVAL;
   1548 	}
   1549 	pt = container_of(it, struct ptimer, pt_itimer);
   1550 	*retval = pt->pt_poverruns;
   1551 	if (*retval >= DELAYTIMER_MAX)
   1552 		*retval = DELAYTIMER_MAX;
   1553 	itimer_unlock();
   1554 
   1555 	return 0;
   1556 }
   1557 
   1558 /*
   1559  * sys___getitimer50:
   1560  *
   1561  *	System call to get the time remaining before a BSD timer fires.
   1562  */
   1563 int
   1564 sys___getitimer50(struct lwp *l, const struct sys___getitimer50_args *uap,
   1565     register_t *retval)
   1566 {
   1567 	/* {
   1568 		syscallarg(int) which;
   1569 		syscallarg(struct itimerval *) itv;
   1570 	} */
   1571 	struct proc *p = l->l_proc;
   1572 	struct itimerval aitv;
   1573 	int error;
   1574 
   1575 	memset(&aitv, 0, sizeof(aitv));
   1576 	error = dogetitimer(p, SCARG(uap, which), &aitv);
   1577 	if (error)
   1578 		return error;
   1579 	return copyout(&aitv, SCARG(uap, itv), sizeof(struct itimerval));
   1580 }
   1581 
   1582 int
   1583 dogetitimer(struct proc *p, int which, struct itimerval *itvp)
   1584 {
   1585 	struct ptimers *pts;
   1586 	struct itimer *it;
   1587 	struct itimerspec its;
   1588 
   1589 	if ((u_int)which > ITIMER_MONOTONIC)
   1590 		return EINVAL;
   1591 
   1592 	itimer_lock();
   1593 	pts = p->p_timers;
   1594 	if (pts == NULL || (it = pts->pts_timers[which]) == NULL) {
   1595 		timerclear(&itvp->it_value);
   1596 		timerclear(&itvp->it_interval);
   1597 	} else {
   1598 		itimer_gettime(it, &its);
   1599 		TIMESPEC_TO_TIMEVAL(&itvp->it_value, &its.it_value);
   1600 		TIMESPEC_TO_TIMEVAL(&itvp->it_interval, &its.it_interval);
   1601 	}
   1602 	itimer_unlock();
   1603 
   1604 	return 0;
   1605 }
   1606 
   1607 /*
   1608  * sys___setitimer50:
   1609  *
   1610  *	System call to set/arm a BSD timer.
   1611  */
   1612 int
   1613 sys___setitimer50(struct lwp *l, const struct sys___setitimer50_args *uap,
   1614     register_t *retval)
   1615 {
   1616 	/* {
   1617 		syscallarg(int) which;
   1618 		syscallarg(const struct itimerval *) itv;
   1619 		syscallarg(struct itimerval *) oitv;
   1620 	} */
   1621 	struct proc *p = l->l_proc;
   1622 	int which = SCARG(uap, which);
   1623 	struct sys___getitimer50_args getargs;
   1624 	const struct itimerval *itvp;
   1625 	struct itimerval aitv;
   1626 	int error;
   1627 
   1628 	itvp = SCARG(uap, itv);
   1629 	if (itvp &&
   1630 	    (error = copyin(itvp, &aitv, sizeof(struct itimerval))) != 0)
   1631 		return error;
   1632 	if (SCARG(uap, oitv) != NULL) {
   1633 		SCARG(&getargs, which) = which;
   1634 		SCARG(&getargs, itv) = SCARG(uap, oitv);
   1635 		if ((error = sys___getitimer50(l, &getargs, retval)) != 0)
   1636 			return error;
   1637 	}
   1638 	if (itvp == 0)
   1639 		return 0;
   1640 
   1641 	return dosetitimer(p, which, &aitv);
   1642 }
   1643 
   1644 int
   1645 dosetitimer(struct proc *p, int which, struct itimerval *itvp)
   1646 {
   1647 	struct timespec now;
   1648 	struct ptimers *pts;
   1649 	struct ptimer *spare;
   1650 	struct itimer *it;
   1651 	struct itlist *itl;
   1652 	int error;
   1653 
   1654 	if ((u_int)which > ITIMER_MONOTONIC)
   1655 		return EINVAL;
   1656 	if (itimerfix(&itvp->it_value) || itimerfix(&itvp->it_interval))
   1657 		return EINVAL;
   1658 
   1659 	/*
   1660 	 * Don't bother allocating data structures if the process just
   1661 	 * wants to clear the timer.
   1662 	 */
   1663 	spare = NULL;
   1664 	pts = p->p_timers;
   1665  retry:
   1666 	if (!timerisset(&itvp->it_value) && (pts == NULL ||
   1667 	    pts->pts_timers[which] == NULL))
   1668 		return 0;
   1669 	if (pts == NULL)
   1670 		pts = ptimers_alloc(p);
   1671 	itimer_lock();
   1672  restart:
   1673 	it = pts->pts_timers[which];
   1674 	if (it == NULL) {
   1675 		struct ptimer *pt;
   1676 
   1677 		if (spare == NULL) {
   1678 			itimer_unlock();
   1679 			spare = kmem_zalloc(sizeof(*spare), KM_SLEEP);
   1680 			goto retry;
   1681 		}
   1682 		pt = spare;
   1683 		spare = NULL;
   1684 
   1685 		it = &pt->pt_itimer;
   1686 		pt->pt_ev.sigev_notify = SIGEV_SIGNAL;
   1687 		pt->pt_ev.sigev_value.sival_int = which;
   1688 
   1689 		switch (which) {
   1690 		case ITIMER_REAL:
   1691 		case ITIMER_MONOTONIC:
   1692 			itl = NULL;
   1693 			pt->pt_ev.sigev_signo = SIGALRM;
   1694 			break;
   1695 		case ITIMER_VIRTUAL:
   1696 			itl = &pts->pts_virtual;
   1697 			pt->pt_ev.sigev_signo = SIGVTALRM;
   1698 			break;
   1699 		case ITIMER_PROF:
   1700 			itl = &pts->pts_prof;
   1701 			pt->pt_ev.sigev_signo = SIGPROF;
   1702 			break;
   1703 		default:
   1704 			panic("%s: can't happen %d", __func__, which);
   1705 		}
   1706 		itimer_init(it, &ptimer_itimer_ops, which, itl);
   1707 		pt->pt_proc = p;
   1708 		pt->pt_entry = which;
   1709 
   1710 		pts->pts_timers[which] = it;
   1711 	}
   1712 
   1713 	TIMEVAL_TO_TIMESPEC(&itvp->it_value, &it->it_time.it_value);
   1714 	TIMEVAL_TO_TIMESPEC(&itvp->it_interval, &it->it_time.it_interval);
   1715 
   1716 	error = 0;
   1717 	if (timespecisset(&it->it_time.it_value)) {
   1718 		/* Convert to absolute time */
   1719 		/* XXX need to wrap in splclock for timecounters case? */
   1720 		switch (which) {
   1721 		case ITIMER_REAL:
   1722 			getnanotime(&now);
   1723 			if (!timespecaddok(&it->it_time.it_value, &now)) {
   1724 				error = EINVAL;
   1725 				goto out;
   1726 			}
   1727 			timespecadd(&it->it_time.it_value, &now,
   1728 			    &it->it_time.it_value);
   1729 			break;
   1730 		case ITIMER_MONOTONIC:
   1731 			getnanouptime(&now);
   1732 			if (!timespecaddok(&it->it_time.it_value, &now)) {
   1733 				error = EINVAL;
   1734 				goto out;
   1735 			}
   1736 			timespecadd(&it->it_time.it_value, &now,
   1737 			    &it->it_time.it_value);
   1738 			break;
   1739 		default:
   1740 			break;
   1741 		}
   1742 	}
   1743 
   1744 	error = itimer_settime(it);
   1745 	if (error == ERESTART) {
   1746 		KASSERT(!CLOCK_VIRTUAL_P(it->it_clockid));
   1747 		goto restart;
   1748 	}
   1749 	KASSERT(error == 0);
   1750 out:
   1751 	itimer_unlock();
   1752 	if (spare != NULL)
   1753 		kmem_free(spare, sizeof(*spare));
   1754 
   1755 	return error;
   1756 }
   1757 
   1758 /*
   1759  * ptimer_tick:
   1760  *
   1761  *	Called from hardclock() to decrement per-process virtual timers.
   1762  */
   1763 void
   1764 ptimer_tick(lwp_t *l, bool user)
   1765 {
   1766 	struct ptimers *pts;
   1767 	struct itimer *it;
   1768 	proc_t *p;
   1769 
   1770 	p = l->l_proc;
   1771 	if (p->p_timers == NULL)
   1772 		return;
   1773 
   1774 	itimer_lock();
   1775 	if ((pts = l->l_proc->p_timers) != NULL) {
   1776 		/*
   1777 		 * Run current process's virtual and profile time, as needed.
   1778 		 */
   1779 		if (user && (it = LIST_FIRST(&pts->pts_virtual)) != NULL)
   1780 			if (itimer_decr(it, tick * 1000))
   1781 				(*it->it_ops->ito_fire)(it);
   1782 		if ((it = LIST_FIRST(&pts->pts_prof)) != NULL)
   1783 			if (itimer_decr(it, tick * 1000))
   1784 				(*it->it_ops->ito_fire)(it);
   1785 	}
   1786 	itimer_unlock();
   1787 }
   1788 
   1789 /*
   1790  * ptimer_intr:
   1791  *
   1792  *	Software interrupt handler for processing per-process
   1793  *	timer expiration.
   1794  */
   1795 static void
   1796 ptimer_intr(void *cookie)
   1797 {
   1798 	ksiginfo_t ksi;
   1799 	struct itimer *it;
   1800 	struct ptimer *pt;
   1801 	proc_t *p;
   1802 
   1803 	mutex_enter(&proc_lock);
   1804 	itimer_lock();
   1805 	while ((pt = TAILQ_FIRST(&ptimer_queue)) != NULL) {
   1806 		it = &pt->pt_itimer;
   1807 
   1808 		TAILQ_REMOVE(&ptimer_queue, pt, pt_chain);
   1809 		KASSERT(pt->pt_queued);
   1810 		pt->pt_queued = false;
   1811 
   1812 		p = pt->pt_proc;
   1813 		if (p->p_timers == NULL) {
   1814 			/* Process is dying. */
   1815 			continue;
   1816 		}
   1817 		if (pt->pt_ev.sigev_notify != SIGEV_SIGNAL) {
   1818 			continue;
   1819 		}
   1820 		if (sigismember(&p->p_sigpend.sp_set, pt->pt_ev.sigev_signo)) {
   1821 			it->it_overruns++;
   1822 			continue;
   1823 		}
   1824 
   1825 		KSI_INIT(&ksi);
   1826 		ksi.ksi_signo = pt->pt_ev.sigev_signo;
   1827 		ksi.ksi_code = SI_TIMER;
   1828 		ksi.ksi_value = pt->pt_ev.sigev_value;
   1829 		pt->pt_poverruns = it->it_overruns;
   1830 		it->it_overruns = 0;
   1831 		itimer_unlock();
   1832 		kpsignal(p, &ksi, NULL);
   1833 		itimer_lock();
   1834 	}
   1835 	itimer_unlock();
   1836 	mutex_exit(&proc_lock);
   1837 }
   1838