Home | History | Annotate | Line # | Download | only in kern
kern_time.c revision 1.189.16.2
      1 /*	$NetBSD: kern_time.c,v 1.189.16.2 2020/04/08 14:08:51 martin Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2000, 2004, 2005, 2007, 2008, 2009 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Christopher G. Demetriou, and by Andrew Doran.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  * Copyright (c) 1982, 1986, 1989, 1993
     34  *	The Regents of the University of California.  All rights reserved.
     35  *
     36  * Redistribution and use in source and binary forms, with or without
     37  * modification, are permitted provided that the following conditions
     38  * are met:
     39  * 1. Redistributions of source code must retain the above copyright
     40  *    notice, this list of conditions and the following disclaimer.
     41  * 2. Redistributions in binary form must reproduce the above copyright
     42  *    notice, this list of conditions and the following disclaimer in the
     43  *    documentation and/or other materials provided with the distribution.
     44  * 3. Neither the name of the University nor the names of its contributors
     45  *    may be used to endorse or promote products derived from this software
     46  *    without specific prior written permission.
     47  *
     48  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     58  * SUCH DAMAGE.
     59  *
     60  *	@(#)kern_time.c	8.4 (Berkeley) 5/26/95
     61  */
     62 
     63 #include <sys/cdefs.h>
     64 __KERNEL_RCSID(0, "$NetBSD: kern_time.c,v 1.189.16.2 2020/04/08 14:08:51 martin Exp $");
     65 
     66 #include <sys/param.h>
     67 #include <sys/resourcevar.h>
     68 #include <sys/kernel.h>
     69 #include <sys/systm.h>
     70 #include <sys/proc.h>
     71 #include <sys/vnode.h>
     72 #include <sys/signalvar.h>
     73 #include <sys/syslog.h>
     74 #include <sys/timetc.h>
     75 #include <sys/timex.h>
     76 #include <sys/kauth.h>
     77 #include <sys/mount.h>
     78 #include <sys/syscallargs.h>
     79 #include <sys/cpu.h>
     80 
     81 static void	timer_intr(void *);
     82 static void	itimerfire(struct ptimer *);
     83 static void	itimerfree(struct ptimers *, int);
     84 
     85 kmutex_t	timer_lock;
     86 
     87 static void	*timer_sih;
     88 static TAILQ_HEAD(, ptimer) timer_queue;
     89 
     90 struct pool ptimer_pool, ptimers_pool;
     91 
     92 #define	CLOCK_VIRTUAL_P(clockid)	\
     93 	((clockid) == CLOCK_VIRTUAL || (clockid) == CLOCK_PROF)
     94 
     95 CTASSERT(ITIMER_REAL == CLOCK_REALTIME);
     96 CTASSERT(ITIMER_VIRTUAL == CLOCK_VIRTUAL);
     97 CTASSERT(ITIMER_PROF == CLOCK_PROF);
     98 CTASSERT(ITIMER_MONOTONIC == CLOCK_MONOTONIC);
     99 
    100 #define	DELAYTIMER_MAX	32
    101 
    102 /*
    103  * Initialize timekeeping.
    104  */
    105 void
    106 time_init(void)
    107 {
    108 
    109 	pool_init(&ptimer_pool, sizeof(struct ptimer), 0, 0, 0, "ptimerpl",
    110 	    &pool_allocator_nointr, IPL_NONE);
    111 	pool_init(&ptimers_pool, sizeof(struct ptimers), 0, 0, 0, "ptimerspl",
    112 	    &pool_allocator_nointr, IPL_NONE);
    113 }
    114 
    115 void
    116 time_init2(void)
    117 {
    118 
    119 	TAILQ_INIT(&timer_queue);
    120 	mutex_init(&timer_lock, MUTEX_DEFAULT, IPL_SCHED);
    121 	timer_sih = softint_establish(SOFTINT_CLOCK | SOFTINT_MPSAFE,
    122 	    timer_intr, NULL);
    123 }
    124 
    125 /* Time of day and interval timer support.
    126  *
    127  * These routines provide the kernel entry points to get and set
    128  * the time-of-day and per-process interval timers.  Subroutines
    129  * here provide support for adding and subtracting timeval structures
    130  * and decrementing interval timers, optionally reloading the interval
    131  * timers when they expire.
    132  */
    133 
    134 /* This function is used by clock_settime and settimeofday */
    135 static int
    136 settime1(struct proc *p, const struct timespec *ts, bool check_kauth)
    137 {
    138 	struct timespec delta, now;
    139 
    140 	/* WHAT DO WE DO ABOUT PENDING REAL-TIME TIMEOUTS??? */
    141 	nanotime(&now);
    142 	timespecsub(ts, &now, &delta);
    143 
    144 	if (check_kauth && kauth_authorize_system(kauth_cred_get(),
    145 	    KAUTH_SYSTEM_TIME, KAUTH_REQ_SYSTEM_TIME_SYSTEM, __UNCONST(ts),
    146 	    &delta, KAUTH_ARG(check_kauth ? false : true)) != 0) {
    147 		return (EPERM);
    148 	}
    149 
    150 #ifdef notyet
    151 	if ((delta.tv_sec < 86400) && securelevel > 0) { /* XXX elad - notyet */
    152 		return (EPERM);
    153 	}
    154 #endif
    155 
    156 	tc_setclock(ts);
    157 
    158 	resettodr();
    159 
    160 	return (0);
    161 }
    162 
    163 int
    164 settime(struct proc *p, struct timespec *ts)
    165 {
    166 	return (settime1(p, ts, true));
    167 }
    168 
    169 /* ARGSUSED */
    170 int
    171 sys___clock_gettime50(struct lwp *l,
    172     const struct sys___clock_gettime50_args *uap, register_t *retval)
    173 {
    174 	/* {
    175 		syscallarg(clockid_t) clock_id;
    176 		syscallarg(struct timespec *) tp;
    177 	} */
    178 	int error;
    179 	struct timespec ats;
    180 
    181 	error = clock_gettime1(SCARG(uap, clock_id), &ats);
    182 	if (error != 0)
    183 		return error;
    184 
    185 	return copyout(&ats, SCARG(uap, tp), sizeof(ats));
    186 }
    187 
    188 /* ARGSUSED */
    189 int
    190 sys___clock_settime50(struct lwp *l,
    191     const struct sys___clock_settime50_args *uap, register_t *retval)
    192 {
    193 	/* {
    194 		syscallarg(clockid_t) clock_id;
    195 		syscallarg(const struct timespec *) tp;
    196 	} */
    197 	int error;
    198 	struct timespec ats;
    199 
    200 	if ((error = copyin(SCARG(uap, tp), &ats, sizeof(ats))) != 0)
    201 		return error;
    202 
    203 	return clock_settime1(l->l_proc, SCARG(uap, clock_id), &ats, true);
    204 }
    205 
    206 
    207 int
    208 clock_settime1(struct proc *p, clockid_t clock_id, const struct timespec *tp,
    209     bool check_kauth)
    210 {
    211 	int error;
    212 
    213 	switch (clock_id) {
    214 	case CLOCK_REALTIME:
    215 		if ((error = settime1(p, tp, check_kauth)) != 0)
    216 			return (error);
    217 		break;
    218 	case CLOCK_MONOTONIC:
    219 		return (EINVAL);	/* read-only clock */
    220 	default:
    221 		return (EINVAL);
    222 	}
    223 
    224 	return 0;
    225 }
    226 
    227 int
    228 sys___clock_getres50(struct lwp *l, const struct sys___clock_getres50_args *uap,
    229     register_t *retval)
    230 {
    231 	/* {
    232 		syscallarg(clockid_t) clock_id;
    233 		syscallarg(struct timespec *) tp;
    234 	} */
    235 	struct timespec ts;
    236 	int error;
    237 
    238 	if ((error = clock_getres1(SCARG(uap, clock_id), &ts)) != 0)
    239 		return error;
    240 
    241 	if (SCARG(uap, tp))
    242 		error = copyout(&ts, SCARG(uap, tp), sizeof(ts));
    243 
    244 	return error;
    245 }
    246 
    247 int
    248 clock_getres1(clockid_t clock_id, struct timespec *ts)
    249 {
    250 
    251 	switch (clock_id) {
    252 	case CLOCK_REALTIME:
    253 	case CLOCK_MONOTONIC:
    254 		ts->tv_sec = 0;
    255 		if (tc_getfrequency() > 1000000000)
    256 			ts->tv_nsec = 1;
    257 		else
    258 			ts->tv_nsec = 1000000000 / tc_getfrequency();
    259 		break;
    260 	default:
    261 		return EINVAL;
    262 	}
    263 
    264 	return 0;
    265 }
    266 
    267 /* ARGSUSED */
    268 int
    269 sys___nanosleep50(struct lwp *l, const struct sys___nanosleep50_args *uap,
    270     register_t *retval)
    271 {
    272 	/* {
    273 		syscallarg(struct timespec *) rqtp;
    274 		syscallarg(struct timespec *) rmtp;
    275 	} */
    276 	struct timespec rmt, rqt;
    277 	int error, error1;
    278 
    279 	error = copyin(SCARG(uap, rqtp), &rqt, sizeof(struct timespec));
    280 	if (error)
    281 		return (error);
    282 
    283 	error = nanosleep1(l, CLOCK_MONOTONIC, 0, &rqt,
    284 	    SCARG(uap, rmtp) ? &rmt : NULL);
    285 	if (SCARG(uap, rmtp) == NULL || (error != 0 && error != EINTR))
    286 		return error;
    287 
    288 	error1 = copyout(&rmt, SCARG(uap, rmtp), sizeof(rmt));
    289 	return error1 ? error1 : error;
    290 }
    291 
    292 /* ARGSUSED */
    293 int
    294 sys_clock_nanosleep(struct lwp *l, const struct sys_clock_nanosleep_args *uap,
    295     register_t *retval)
    296 {
    297 	/* {
    298 		syscallarg(clockid_t) clock_id;
    299 		syscallarg(int) flags;
    300 		syscallarg(struct timespec *) rqtp;
    301 		syscallarg(struct timespec *) rmtp;
    302 	} */
    303 	struct timespec rmt, rqt;
    304 	int error, error1;
    305 
    306 	error = copyin(SCARG(uap, rqtp), &rqt, sizeof(struct timespec));
    307 	if (error)
    308 		goto out;
    309 
    310 	error = nanosleep1(l, SCARG(uap, clock_id), SCARG(uap, flags), &rqt,
    311 	    SCARG(uap, rmtp) ? &rmt : NULL);
    312 	if (SCARG(uap, rmtp) == NULL || (error != 0 && error != EINTR))
    313 		goto out;
    314 
    315 	if ((SCARG(uap, flags) & TIMER_ABSTIME) == 0 &&
    316 	    (error1 = copyout(&rmt, SCARG(uap, rmtp), sizeof(rmt))) != 0)
    317 		error = error1;
    318 out:
    319 	*retval = error;
    320 	return 0;
    321 }
    322 
    323 int
    324 nanosleep1(struct lwp *l, clockid_t clock_id, int flags, struct timespec *rqt,
    325     struct timespec *rmt)
    326 {
    327 	struct timespec rmtstart;
    328 	int error, timo;
    329 
    330 	if ((error = ts2timo(clock_id, flags, rqt, &timo, &rmtstart)) != 0) {
    331 		if (error == ETIMEDOUT) {
    332 			error = 0;
    333 			if (rmt != NULL)
    334 				rmt->tv_sec = rmt->tv_nsec = 0;
    335 		}
    336 		return error;
    337 	}
    338 
    339 	/*
    340 	 * Avoid inadvertently sleeping forever
    341 	 */
    342 	if (timo == 0)
    343 		timo = 1;
    344 again:
    345 	error = kpause("nanoslp", true, timo, NULL);
    346 	if (error == EWOULDBLOCK)
    347 		error = 0;
    348 	if (rmt != NULL || error == 0) {
    349 		struct timespec rmtend;
    350 		struct timespec t0;
    351 		struct timespec *t;
    352 
    353 		(void)clock_gettime1(clock_id, &rmtend);
    354 		t = (rmt != NULL) ? rmt : &t0;
    355 		if (flags & TIMER_ABSTIME) {
    356 			timespecsub(rqt, &rmtend, t);
    357 		} else {
    358 			timespecsub(&rmtend, &rmtstart, t);
    359 			timespecsub(rqt, t, t);
    360 		}
    361 		if (t->tv_sec < 0)
    362 			timespecclear(t);
    363 		if (error == 0) {
    364 			timo = tstohz(t);
    365 			if (timo > 0)
    366 				goto again;
    367 		}
    368 	}
    369 
    370 	if (error == ERESTART)
    371 		error = EINTR;
    372 
    373 	return error;
    374 }
    375 
    376 int
    377 sys_clock_getcpuclockid2(struct lwp *l,
    378     const struct sys_clock_getcpuclockid2_args *uap,
    379     register_t *retval)
    380 {
    381 	/* {
    382 		syscallarg(idtype_t idtype;
    383 		syscallarg(id_t id);
    384 		syscallarg(clockid_t *)clock_id;
    385 	} */
    386 	pid_t pid;
    387 	lwpid_t lid;
    388 	clockid_t clock_id;
    389 	id_t id = SCARG(uap, id);
    390 
    391 	switch (SCARG(uap, idtype)) {
    392 	case P_PID:
    393 		pid = id == 0 ? l->l_proc->p_pid : id;
    394 		clock_id = CLOCK_PROCESS_CPUTIME_ID | pid;
    395 		break;
    396 	case P_LWPID:
    397 		lid = id == 0 ? l->l_lid : id;
    398 		clock_id = CLOCK_THREAD_CPUTIME_ID | lid;
    399 		break;
    400 	default:
    401 		return EINVAL;
    402 	}
    403 	return copyout(&clock_id, SCARG(uap, clock_id), sizeof(clock_id));
    404 }
    405 
    406 /* ARGSUSED */
    407 int
    408 sys___gettimeofday50(struct lwp *l, const struct sys___gettimeofday50_args *uap,
    409     register_t *retval)
    410 {
    411 	/* {
    412 		syscallarg(struct timeval *) tp;
    413 		syscallarg(void *) tzp;		really "struct timezone *";
    414 	} */
    415 	struct timeval atv;
    416 	int error = 0;
    417 	struct timezone tzfake;
    418 
    419 	if (SCARG(uap, tp)) {
    420 		memset(&atv, 0, sizeof(atv));
    421 		microtime(&atv);
    422 		error = copyout(&atv, SCARG(uap, tp), sizeof(atv));
    423 		if (error)
    424 			return (error);
    425 	}
    426 	if (SCARG(uap, tzp)) {
    427 		/*
    428 		 * NetBSD has no kernel notion of time zone, so we just
    429 		 * fake up a timezone struct and return it if demanded.
    430 		 */
    431 		tzfake.tz_minuteswest = 0;
    432 		tzfake.tz_dsttime = 0;
    433 		error = copyout(&tzfake, SCARG(uap, tzp), sizeof(tzfake));
    434 	}
    435 	return (error);
    436 }
    437 
    438 /* ARGSUSED */
    439 int
    440 sys___settimeofday50(struct lwp *l, const struct sys___settimeofday50_args *uap,
    441     register_t *retval)
    442 {
    443 	/* {
    444 		syscallarg(const struct timeval *) tv;
    445 		syscallarg(const void *) tzp; really "const struct timezone *";
    446 	} */
    447 
    448 	return settimeofday1(SCARG(uap, tv), true, SCARG(uap, tzp), l, true);
    449 }
    450 
    451 int
    452 settimeofday1(const struct timeval *utv, bool userspace,
    453     const void *utzp, struct lwp *l, bool check_kauth)
    454 {
    455 	struct timeval atv;
    456 	struct timespec ts;
    457 	int error;
    458 
    459 	/* Verify all parameters before changing time. */
    460 
    461 	/*
    462 	 * NetBSD has no kernel notion of time zone, and only an
    463 	 * obsolete program would try to set it, so we log a warning.
    464 	 */
    465 	if (utzp)
    466 		log(LOG_WARNING, "pid %d attempted to set the "
    467 		    "(obsolete) kernel time zone\n", l->l_proc->p_pid);
    468 
    469 	if (utv == NULL)
    470 		return 0;
    471 
    472 	if (userspace) {
    473 		if ((error = copyin(utv, &atv, sizeof(atv))) != 0)
    474 			return error;
    475 		utv = &atv;
    476 	}
    477 
    478 	TIMEVAL_TO_TIMESPEC(utv, &ts);
    479 	return settime1(l->l_proc, &ts, check_kauth);
    480 }
    481 
    482 int	time_adjusted;			/* set if an adjustment is made */
    483 
    484 /* ARGSUSED */
    485 int
    486 sys___adjtime50(struct lwp *l, const struct sys___adjtime50_args *uap,
    487     register_t *retval)
    488 {
    489 	/* {
    490 		syscallarg(const struct timeval *) delta;
    491 		syscallarg(struct timeval *) olddelta;
    492 	} */
    493 	int error;
    494 	struct timeval atv, oldatv;
    495 
    496 	if ((error = kauth_authorize_system(l->l_cred, KAUTH_SYSTEM_TIME,
    497 	    KAUTH_REQ_SYSTEM_TIME_ADJTIME, NULL, NULL, NULL)) != 0)
    498 		return error;
    499 
    500 	if (SCARG(uap, delta)) {
    501 		error = copyin(SCARG(uap, delta), &atv,
    502 		    sizeof(*SCARG(uap, delta)));
    503 		if (error)
    504 			return (error);
    505 	}
    506 	adjtime1(SCARG(uap, delta) ? &atv : NULL,
    507 	    SCARG(uap, olddelta) ? &oldatv : NULL, l->l_proc);
    508 	if (SCARG(uap, olddelta))
    509 		error = copyout(&oldatv, SCARG(uap, olddelta),
    510 		    sizeof(*SCARG(uap, olddelta)));
    511 	return error;
    512 }
    513 
    514 void
    515 adjtime1(const struct timeval *delta, struct timeval *olddelta, struct proc *p)
    516 {
    517 	extern int64_t time_adjtime;  /* in kern_ntptime.c */
    518 
    519 	if (olddelta) {
    520 		memset(olddelta, 0, sizeof(*olddelta));
    521 		mutex_spin_enter(&timecounter_lock);
    522 		olddelta->tv_sec = time_adjtime / 1000000;
    523 		olddelta->tv_usec = time_adjtime % 1000000;
    524 		if (olddelta->tv_usec < 0) {
    525 			olddelta->tv_usec += 1000000;
    526 			olddelta->tv_sec--;
    527 		}
    528 		mutex_spin_exit(&timecounter_lock);
    529 	}
    530 
    531 	if (delta) {
    532 		mutex_spin_enter(&timecounter_lock);
    533 		time_adjtime = delta->tv_sec * 1000000 + delta->tv_usec;
    534 
    535 		if (time_adjtime) {
    536 			/* We need to save the system time during shutdown */
    537 			time_adjusted |= 1;
    538 		}
    539 		mutex_spin_exit(&timecounter_lock);
    540 	}
    541 }
    542 
    543 /*
    544  * Interval timer support. Both the BSD getitimer() family and the POSIX
    545  * timer_*() family of routines are supported.
    546  *
    547  * All timers are kept in an array pointed to by p_timers, which is
    548  * allocated on demand - many processes don't use timers at all. The
    549  * first four elements in this array are reserved for the BSD timers:
    550  * element 0 is ITIMER_REAL, element 1 is ITIMER_VIRTUAL, element
    551  * 2 is ITIMER_PROF, and element 3 is ITIMER_MONOTONIC. The rest may be
    552  * allocated by the timer_create() syscall.
    553  *
    554  * Realtime timers are kept in the ptimer structure as an absolute
    555  * time; virtual time timers are kept as a linked list of deltas.
    556  * Virtual time timers are processed in the hardclock() routine of
    557  * kern_clock.c.  The real time timer is processed by a callout
    558  * routine, called from the softclock() routine.  Since a callout may
    559  * be delayed in real time due to interrupt processing in the system,
    560  * it is possible for the real time timeout routine (realtimeexpire,
    561  * given below), to be delayed in real time past when it is supposed
    562  * to occur.  It does not suffice, therefore, to reload the real timer
    563  * .it_value from the real time timers .it_interval.  Rather, we
    564  * compute the next time in absolute time the timer should go off.  */
    565 
    566 /* Allocate a POSIX realtime timer. */
    567 int
    568 sys_timer_create(struct lwp *l, const struct sys_timer_create_args *uap,
    569     register_t *retval)
    570 {
    571 	/* {
    572 		syscallarg(clockid_t) clock_id;
    573 		syscallarg(struct sigevent *) evp;
    574 		syscallarg(timer_t *) timerid;
    575 	} */
    576 
    577 	return timer_create1(SCARG(uap, timerid), SCARG(uap, clock_id),
    578 	    SCARG(uap, evp), copyin, l);
    579 }
    580 
    581 int
    582 timer_create1(timer_t *tid, clockid_t id, struct sigevent *evp,
    583     copyin_t fetch_event, struct lwp *l)
    584 {
    585 	int error;
    586 	timer_t timerid;
    587 	struct ptimers *pts;
    588 	struct ptimer *pt;
    589 	struct proc *p;
    590 
    591 	p = l->l_proc;
    592 
    593 	if ((u_int)id > CLOCK_MONOTONIC)
    594 		return (EINVAL);
    595 
    596 	if ((pts = p->p_timers) == NULL)
    597 		pts = timers_alloc(p);
    598 
    599 	pt = pool_get(&ptimer_pool, PR_WAITOK | PR_ZERO);
    600 	if (evp != NULL) {
    601 		if (((error =
    602 		    (*fetch_event)(evp, &pt->pt_ev, sizeof(pt->pt_ev))) != 0) ||
    603 		    ((pt->pt_ev.sigev_notify < SIGEV_NONE) ||
    604 			(pt->pt_ev.sigev_notify > SIGEV_SA)) ||
    605 			(pt->pt_ev.sigev_notify == SIGEV_SIGNAL &&
    606 			 (pt->pt_ev.sigev_signo <= 0 ||
    607 			  pt->pt_ev.sigev_signo >= NSIG))) {
    608 			pool_put(&ptimer_pool, pt);
    609 			return (error ? error : EINVAL);
    610 		}
    611 	}
    612 
    613 	/* Find a free timer slot, skipping those reserved for setitimer(). */
    614 	mutex_spin_enter(&timer_lock);
    615 	for (timerid = TIMER_MIN; timerid < TIMER_MAX; timerid++)
    616 		if (pts->pts_timers[timerid] == NULL)
    617 			break;
    618 	if (timerid == TIMER_MAX) {
    619 		mutex_spin_exit(&timer_lock);
    620 		pool_put(&ptimer_pool, pt);
    621 		return EAGAIN;
    622 	}
    623 	if (evp == NULL) {
    624 		pt->pt_ev.sigev_notify = SIGEV_SIGNAL;
    625 		switch (id) {
    626 		case CLOCK_REALTIME:
    627 		case CLOCK_MONOTONIC:
    628 			pt->pt_ev.sigev_signo = SIGALRM;
    629 			break;
    630 		case CLOCK_VIRTUAL:
    631 			pt->pt_ev.sigev_signo = SIGVTALRM;
    632 			break;
    633 		case CLOCK_PROF:
    634 			pt->pt_ev.sigev_signo = SIGPROF;
    635 			break;
    636 		}
    637 		pt->pt_ev.sigev_value.sival_int = timerid;
    638 	}
    639 	pt->pt_info.ksi_signo = pt->pt_ev.sigev_signo;
    640 	pt->pt_info.ksi_errno = 0;
    641 	pt->pt_info.ksi_code = 0;
    642 	pt->pt_info.ksi_pid = p->p_pid;
    643 	pt->pt_info.ksi_uid = kauth_cred_getuid(l->l_cred);
    644 	pt->pt_info.ksi_value = pt->pt_ev.sigev_value;
    645 	pt->pt_type = id;
    646 	pt->pt_proc = p;
    647 	pt->pt_overruns = 0;
    648 	pt->pt_poverruns = 0;
    649 	pt->pt_entry = timerid;
    650 	pt->pt_queued = false;
    651 	timespecclear(&pt->pt_time.it_value);
    652 	if (!CLOCK_VIRTUAL_P(id))
    653 		callout_init(&pt->pt_ch, CALLOUT_MPSAFE);
    654 	else
    655 		pt->pt_active = 0;
    656 
    657 	pts->pts_timers[timerid] = pt;
    658 	mutex_spin_exit(&timer_lock);
    659 
    660 	return copyout(&timerid, tid, sizeof(timerid));
    661 }
    662 
    663 /* Delete a POSIX realtime timer */
    664 int
    665 sys_timer_delete(struct lwp *l, const struct sys_timer_delete_args *uap,
    666     register_t *retval)
    667 {
    668 	/* {
    669 		syscallarg(timer_t) timerid;
    670 	} */
    671 	struct proc *p = l->l_proc;
    672 	timer_t timerid;
    673 	struct ptimers *pts;
    674 	struct ptimer *pt, *ptn;
    675 
    676 	timerid = SCARG(uap, timerid);
    677 	pts = p->p_timers;
    678 
    679 	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
    680 		return (EINVAL);
    681 
    682 	mutex_spin_enter(&timer_lock);
    683 	if ((pt = pts->pts_timers[timerid]) == NULL) {
    684 		mutex_spin_exit(&timer_lock);
    685 		return (EINVAL);
    686 	}
    687 	if (CLOCK_VIRTUAL_P(pt->pt_type)) {
    688 		if (pt->pt_active) {
    689 			ptn = LIST_NEXT(pt, pt_list);
    690 			LIST_REMOVE(pt, pt_list);
    691 			for ( ; ptn; ptn = LIST_NEXT(ptn, pt_list))
    692 				timespecadd(&pt->pt_time.it_value,
    693 				    &ptn->pt_time.it_value,
    694 				    &ptn->pt_time.it_value);
    695 			pt->pt_active = 0;
    696 		}
    697 	}
    698 	itimerfree(pts, timerid);
    699 
    700 	return (0);
    701 }
    702 
    703 /*
    704  * Set up the given timer. The value in pt->pt_time.it_value is taken
    705  * to be an absolute time for CLOCK_REALTIME/CLOCK_MONOTONIC timers and
    706  * a relative time for CLOCK_VIRTUAL/CLOCK_PROF timers.
    707  */
    708 void
    709 timer_settime(struct ptimer *pt)
    710 {
    711 	struct ptimer *ptn, *pptn;
    712 	struct ptlist *ptl;
    713 
    714 	KASSERT(mutex_owned(&timer_lock));
    715 
    716 	if (!CLOCK_VIRTUAL_P(pt->pt_type)) {
    717 		callout_halt(&pt->pt_ch, &timer_lock);
    718 		if (timespecisset(&pt->pt_time.it_value)) {
    719 			/*
    720 			 * Don't need to check tshzto() return value, here.
    721 			 * callout_reset() does it for us.
    722 			 */
    723 			callout_reset(&pt->pt_ch,
    724 			    pt->pt_type == CLOCK_MONOTONIC ?
    725 			    tshztoup(&pt->pt_time.it_value) :
    726 			    tshzto(&pt->pt_time.it_value),
    727 			    realtimerexpire, pt);
    728 		}
    729 	} else {
    730 		if (pt->pt_active) {
    731 			ptn = LIST_NEXT(pt, pt_list);
    732 			LIST_REMOVE(pt, pt_list);
    733 			for ( ; ptn; ptn = LIST_NEXT(ptn, pt_list))
    734 				timespecadd(&pt->pt_time.it_value,
    735 				    &ptn->pt_time.it_value,
    736 				    &ptn->pt_time.it_value);
    737 		}
    738 		if (timespecisset(&pt->pt_time.it_value)) {
    739 			if (pt->pt_type == CLOCK_VIRTUAL)
    740 				ptl = &pt->pt_proc->p_timers->pts_virtual;
    741 			else
    742 				ptl = &pt->pt_proc->p_timers->pts_prof;
    743 
    744 			for (ptn = LIST_FIRST(ptl), pptn = NULL;
    745 			     ptn && timespeccmp(&pt->pt_time.it_value,
    746 				 &ptn->pt_time.it_value, >);
    747 			     pptn = ptn, ptn = LIST_NEXT(ptn, pt_list))
    748 				timespecsub(&pt->pt_time.it_value,
    749 				    &ptn->pt_time.it_value,
    750 				    &pt->pt_time.it_value);
    751 
    752 			if (pptn)
    753 				LIST_INSERT_AFTER(pptn, pt, pt_list);
    754 			else
    755 				LIST_INSERT_HEAD(ptl, pt, pt_list);
    756 
    757 			for ( ; ptn ; ptn = LIST_NEXT(ptn, pt_list))
    758 				timespecsub(&ptn->pt_time.it_value,
    759 				    &pt->pt_time.it_value,
    760 				    &ptn->pt_time.it_value);
    761 
    762 			pt->pt_active = 1;
    763 		} else
    764 			pt->pt_active = 0;
    765 	}
    766 }
    767 
    768 void
    769 timer_gettime(struct ptimer *pt, struct itimerspec *aits)
    770 {
    771 	struct timespec now;
    772 	struct ptimer *ptn;
    773 
    774 	KASSERT(mutex_owned(&timer_lock));
    775 
    776 	*aits = pt->pt_time;
    777 	if (!CLOCK_VIRTUAL_P(pt->pt_type)) {
    778 		/*
    779 		 * Convert from absolute to relative time in .it_value
    780 		 * part of real time timer.  If time for real time
    781 		 * timer has passed return 0, else return difference
    782 		 * between current time and time for the timer to go
    783 		 * off.
    784 		 */
    785 		if (timespecisset(&aits->it_value)) {
    786 			if (pt->pt_type == CLOCK_REALTIME) {
    787 				getnanotime(&now);
    788 			} else { /* CLOCK_MONOTONIC */
    789 				getnanouptime(&now);
    790 			}
    791 			if (timespeccmp(&aits->it_value, &now, <))
    792 				timespecclear(&aits->it_value);
    793 			else
    794 				timespecsub(&aits->it_value, &now,
    795 				    &aits->it_value);
    796 		}
    797 	} else if (pt->pt_active) {
    798 		if (pt->pt_type == CLOCK_VIRTUAL)
    799 			ptn = LIST_FIRST(&pt->pt_proc->p_timers->pts_virtual);
    800 		else
    801 			ptn = LIST_FIRST(&pt->pt_proc->p_timers->pts_prof);
    802 		for ( ; ptn && ptn != pt; ptn = LIST_NEXT(ptn, pt_list))
    803 			timespecadd(&aits->it_value,
    804 			    &ptn->pt_time.it_value, &aits->it_value);
    805 		KASSERT(ptn != NULL); /* pt should be findable on the list */
    806 	} else
    807 		timespecclear(&aits->it_value);
    808 }
    809 
    810 
    811 
    812 /* Set and arm a POSIX realtime timer */
    813 int
    814 sys___timer_settime50(struct lwp *l,
    815     const struct sys___timer_settime50_args *uap,
    816     register_t *retval)
    817 {
    818 	/* {
    819 		syscallarg(timer_t) timerid;
    820 		syscallarg(int) flags;
    821 		syscallarg(const struct itimerspec *) value;
    822 		syscallarg(struct itimerspec *) ovalue;
    823 	} */
    824 	int error;
    825 	struct itimerspec value, ovalue, *ovp = NULL;
    826 
    827 	if ((error = copyin(SCARG(uap, value), &value,
    828 	    sizeof(struct itimerspec))) != 0)
    829 		return (error);
    830 
    831 	if (SCARG(uap, ovalue))
    832 		ovp = &ovalue;
    833 
    834 	if ((error = dotimer_settime(SCARG(uap, timerid), &value, ovp,
    835 	    SCARG(uap, flags), l->l_proc)) != 0)
    836 		return error;
    837 
    838 	if (ovp)
    839 		return copyout(&ovalue, SCARG(uap, ovalue),
    840 		    sizeof(struct itimerspec));
    841 	return 0;
    842 }
    843 
    844 int
    845 dotimer_settime(int timerid, struct itimerspec *value,
    846     struct itimerspec *ovalue, int flags, struct proc *p)
    847 {
    848 	struct timespec now;
    849 	struct itimerspec val, oval;
    850 	struct ptimers *pts;
    851 	struct ptimer *pt;
    852 	int error;
    853 
    854 	pts = p->p_timers;
    855 
    856 	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
    857 		return EINVAL;
    858 	val = *value;
    859 	if ((error = itimespecfix(&val.it_value)) != 0 ||
    860 	    (error = itimespecfix(&val.it_interval)) != 0)
    861 		return error;
    862 
    863 	mutex_spin_enter(&timer_lock);
    864 	if ((pt = pts->pts_timers[timerid]) == NULL) {
    865 		mutex_spin_exit(&timer_lock);
    866 		return EINVAL;
    867 	}
    868 
    869 	oval = pt->pt_time;
    870 	pt->pt_time = val;
    871 
    872 	/*
    873 	 * If we've been passed a relative time for a realtime timer,
    874 	 * convert it to absolute; if an absolute time for a virtual
    875 	 * timer, convert it to relative and make sure we don't set it
    876 	 * to zero, which would cancel the timer, or let it go
    877 	 * negative, which would confuse the comparison tests.
    878 	 */
    879 	if (timespecisset(&pt->pt_time.it_value)) {
    880 		if (!CLOCK_VIRTUAL_P(pt->pt_type)) {
    881 			if ((flags & TIMER_ABSTIME) == 0) {
    882 				if (pt->pt_type == CLOCK_REALTIME) {
    883 					getnanotime(&now);
    884 				} else { /* CLOCK_MONOTONIC */
    885 					getnanouptime(&now);
    886 				}
    887 				timespecadd(&pt->pt_time.it_value, &now,
    888 				    &pt->pt_time.it_value);
    889 			}
    890 		} else {
    891 			if ((flags & TIMER_ABSTIME) != 0) {
    892 				getnanotime(&now);
    893 				timespecsub(&pt->pt_time.it_value, &now,
    894 				    &pt->pt_time.it_value);
    895 				if (!timespecisset(&pt->pt_time.it_value) ||
    896 				    pt->pt_time.it_value.tv_sec < 0) {
    897 					pt->pt_time.it_value.tv_sec = 0;
    898 					pt->pt_time.it_value.tv_nsec = 1;
    899 				}
    900 			}
    901 		}
    902 	}
    903 
    904 	timer_settime(pt);
    905 	mutex_spin_exit(&timer_lock);
    906 
    907 	if (ovalue)
    908 		*ovalue = oval;
    909 
    910 	return (0);
    911 }
    912 
    913 /* Return the time remaining until a POSIX timer fires. */
    914 int
    915 sys___timer_gettime50(struct lwp *l,
    916     const struct sys___timer_gettime50_args *uap, register_t *retval)
    917 {
    918 	/* {
    919 		syscallarg(timer_t) timerid;
    920 		syscallarg(struct itimerspec *) value;
    921 	} */
    922 	struct itimerspec its;
    923 	int error;
    924 
    925 	if ((error = dotimer_gettime(SCARG(uap, timerid), l->l_proc,
    926 	    &its)) != 0)
    927 		return error;
    928 
    929 	return copyout(&its, SCARG(uap, value), sizeof(its));
    930 }
    931 
    932 int
    933 dotimer_gettime(int timerid, struct proc *p, struct itimerspec *its)
    934 {
    935 	struct ptimer *pt;
    936 	struct ptimers *pts;
    937 
    938 	pts = p->p_timers;
    939 	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
    940 		return (EINVAL);
    941 	mutex_spin_enter(&timer_lock);
    942 	if ((pt = pts->pts_timers[timerid]) == NULL) {
    943 		mutex_spin_exit(&timer_lock);
    944 		return (EINVAL);
    945 	}
    946 	timer_gettime(pt, its);
    947 	mutex_spin_exit(&timer_lock);
    948 
    949 	return 0;
    950 }
    951 
    952 /*
    953  * Return the count of the number of times a periodic timer expired
    954  * while a notification was already pending. The counter is reset when
    955  * a timer expires and a notification can be posted.
    956  */
    957 int
    958 sys_timer_getoverrun(struct lwp *l, const struct sys_timer_getoverrun_args *uap,
    959     register_t *retval)
    960 {
    961 	/* {
    962 		syscallarg(timer_t) timerid;
    963 	} */
    964 	struct proc *p = l->l_proc;
    965 	struct ptimers *pts;
    966 	int timerid;
    967 	struct ptimer *pt;
    968 
    969 	timerid = SCARG(uap, timerid);
    970 
    971 	pts = p->p_timers;
    972 	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
    973 		return (EINVAL);
    974 	mutex_spin_enter(&timer_lock);
    975 	if ((pt = pts->pts_timers[timerid]) == NULL) {
    976 		mutex_spin_exit(&timer_lock);
    977 		return (EINVAL);
    978 	}
    979 	*retval = pt->pt_poverruns;
    980 	if (*retval >= DELAYTIMER_MAX)
    981 		*retval = DELAYTIMER_MAX;
    982 	mutex_spin_exit(&timer_lock);
    983 
    984 	return (0);
    985 }
    986 
    987 /*
    988  * Real interval timer expired:
    989  * send process whose timer expired an alarm signal.
    990  * If time is not set up to reload, then just return.
    991  * Else compute next time timer should go off which is > current time.
    992  * This is where delay in processing this timeout causes multiple
    993  * SIGALRM calls to be compressed into one.
    994  */
    995 void
    996 realtimerexpire(void *arg)
    997 {
    998 	uint64_t last_val, next_val, interval, now_ns;
    999 	struct timespec now, next;
   1000 	struct ptimer *pt;
   1001 	int backwards;
   1002 
   1003 	pt = arg;
   1004 
   1005 	mutex_spin_enter(&timer_lock);
   1006 	itimerfire(pt);
   1007 
   1008 	if (!timespecisset(&pt->pt_time.it_interval)) {
   1009 		timespecclear(&pt->pt_time.it_value);
   1010 		mutex_spin_exit(&timer_lock);
   1011 		return;
   1012 	}
   1013 
   1014 	if (pt->pt_type == CLOCK_MONOTONIC) {
   1015 		getnanouptime(&now);
   1016 	} else {
   1017 		getnanotime(&now);
   1018 	}
   1019 	backwards = (timespeccmp(&pt->pt_time.it_value, &now, >));
   1020 	timespecadd(&pt->pt_time.it_value, &pt->pt_time.it_interval, &next);
   1021 	/* Handle the easy case of non-overflown timers first. */
   1022 	if (!backwards && timespeccmp(&next, &now, >)) {
   1023 		pt->pt_time.it_value = next;
   1024 	} else {
   1025 		now_ns = timespec2ns(&now);
   1026 		last_val = timespec2ns(&pt->pt_time.it_value);
   1027 		interval = timespec2ns(&pt->pt_time.it_interval);
   1028 
   1029 		next_val = now_ns +
   1030 		    (now_ns - last_val + interval - 1) % interval;
   1031 
   1032 		if (backwards)
   1033 			next_val += interval;
   1034 		else
   1035 			pt->pt_overruns += (now_ns - last_val) / interval;
   1036 
   1037 		pt->pt_time.it_value.tv_sec = next_val / 1000000000;
   1038 		pt->pt_time.it_value.tv_nsec = next_val % 1000000000;
   1039 	}
   1040 
   1041 	/*
   1042 	 * Don't need to check tshzto() return value, here.
   1043 	 * callout_reset() does it for us.
   1044 	 */
   1045 	callout_reset(&pt->pt_ch, pt->pt_type == CLOCK_MONOTONIC ?
   1046 	    tshztoup(&pt->pt_time.it_value) : tshzto(&pt->pt_time.it_value),
   1047 	    realtimerexpire, pt);
   1048 	mutex_spin_exit(&timer_lock);
   1049 }
   1050 
   1051 /* BSD routine to get the value of an interval timer. */
   1052 /* ARGSUSED */
   1053 int
   1054 sys___getitimer50(struct lwp *l, const struct sys___getitimer50_args *uap,
   1055     register_t *retval)
   1056 {
   1057 	/* {
   1058 		syscallarg(int) which;
   1059 		syscallarg(struct itimerval *) itv;
   1060 	} */
   1061 	struct proc *p = l->l_proc;
   1062 	struct itimerval aitv;
   1063 	int error;
   1064 
   1065 	memset(&aitv, 0, sizeof(aitv));
   1066 	error = dogetitimer(p, SCARG(uap, which), &aitv);
   1067 	if (error)
   1068 		return error;
   1069 	return (copyout(&aitv, SCARG(uap, itv), sizeof(struct itimerval)));
   1070 }
   1071 
   1072 int
   1073 dogetitimer(struct proc *p, int which, struct itimerval *itvp)
   1074 {
   1075 	struct ptimers *pts;
   1076 	struct ptimer *pt;
   1077 	struct itimerspec its;
   1078 
   1079 	if ((u_int)which > ITIMER_MONOTONIC)
   1080 		return (EINVAL);
   1081 
   1082 	mutex_spin_enter(&timer_lock);
   1083 	pts = p->p_timers;
   1084 	if (pts == NULL || (pt = pts->pts_timers[which]) == NULL) {
   1085 		timerclear(&itvp->it_value);
   1086 		timerclear(&itvp->it_interval);
   1087 	} else {
   1088 		timer_gettime(pt, &its);
   1089 		TIMESPEC_TO_TIMEVAL(&itvp->it_value, &its.it_value);
   1090 		TIMESPEC_TO_TIMEVAL(&itvp->it_interval, &its.it_interval);
   1091 	}
   1092 	mutex_spin_exit(&timer_lock);
   1093 
   1094 	return 0;
   1095 }
   1096 
   1097 /* BSD routine to set/arm an interval timer. */
   1098 /* ARGSUSED */
   1099 int
   1100 sys___setitimer50(struct lwp *l, const struct sys___setitimer50_args *uap,
   1101     register_t *retval)
   1102 {
   1103 	/* {
   1104 		syscallarg(int) which;
   1105 		syscallarg(const struct itimerval *) itv;
   1106 		syscallarg(struct itimerval *) oitv;
   1107 	} */
   1108 	struct proc *p = l->l_proc;
   1109 	int which = SCARG(uap, which);
   1110 	struct sys___getitimer50_args getargs;
   1111 	const struct itimerval *itvp;
   1112 	struct itimerval aitv;
   1113 	int error;
   1114 
   1115 	if ((u_int)which > ITIMER_MONOTONIC)
   1116 		return (EINVAL);
   1117 	itvp = SCARG(uap, itv);
   1118 	if (itvp &&
   1119 	    (error = copyin(itvp, &aitv, sizeof(struct itimerval))) != 0)
   1120 		return (error);
   1121 	if (SCARG(uap, oitv) != NULL) {
   1122 		SCARG(&getargs, which) = which;
   1123 		SCARG(&getargs, itv) = SCARG(uap, oitv);
   1124 		if ((error = sys___getitimer50(l, &getargs, retval)) != 0)
   1125 			return (error);
   1126 	}
   1127 	if (itvp == 0)
   1128 		return (0);
   1129 
   1130 	return dosetitimer(p, which, &aitv);
   1131 }
   1132 
   1133 int
   1134 dosetitimer(struct proc *p, int which, struct itimerval *itvp)
   1135 {
   1136 	struct timespec now;
   1137 	struct ptimers *pts;
   1138 	struct ptimer *pt, *spare;
   1139 
   1140 	KASSERT((u_int)which <= CLOCK_MONOTONIC);
   1141 	if (itimerfix(&itvp->it_value) || itimerfix(&itvp->it_interval))
   1142 		return (EINVAL);
   1143 
   1144 	/*
   1145 	 * Don't bother allocating data structures if the process just
   1146 	 * wants to clear the timer.
   1147 	 */
   1148 	spare = NULL;
   1149 	pts = p->p_timers;
   1150  retry:
   1151 	if (!timerisset(&itvp->it_value) && (pts == NULL ||
   1152 	    pts->pts_timers[which] == NULL))
   1153 		return (0);
   1154 	if (pts == NULL)
   1155 		pts = timers_alloc(p);
   1156 	mutex_spin_enter(&timer_lock);
   1157 	pt = pts->pts_timers[which];
   1158 	if (pt == NULL) {
   1159 		if (spare == NULL) {
   1160 			mutex_spin_exit(&timer_lock);
   1161 			spare = pool_get(&ptimer_pool, PR_WAITOK | PR_ZERO);
   1162 			goto retry;
   1163 		}
   1164 		pt = spare;
   1165 		spare = NULL;
   1166 		pt->pt_ev.sigev_notify = SIGEV_SIGNAL;
   1167 		pt->pt_ev.sigev_value.sival_int = which;
   1168 		pt->pt_overruns = 0;
   1169 		pt->pt_proc = p;
   1170 		pt->pt_type = which;
   1171 		pt->pt_entry = which;
   1172 		pt->pt_queued = false;
   1173 		if (!CLOCK_VIRTUAL_P(which))
   1174 			callout_init(&pt->pt_ch, CALLOUT_MPSAFE);
   1175 		else
   1176 			pt->pt_active = 0;
   1177 
   1178 		switch (which) {
   1179 		case ITIMER_REAL:
   1180 		case ITIMER_MONOTONIC:
   1181 			pt->pt_ev.sigev_signo = SIGALRM;
   1182 			break;
   1183 		case ITIMER_VIRTUAL:
   1184 			pt->pt_ev.sigev_signo = SIGVTALRM;
   1185 			break;
   1186 		case ITIMER_PROF:
   1187 			pt->pt_ev.sigev_signo = SIGPROF;
   1188 			break;
   1189 		}
   1190 		pts->pts_timers[which] = pt;
   1191 	}
   1192 
   1193 	TIMEVAL_TO_TIMESPEC(&itvp->it_value, &pt->pt_time.it_value);
   1194 	TIMEVAL_TO_TIMESPEC(&itvp->it_interval, &pt->pt_time.it_interval);
   1195 
   1196 	if (timespecisset(&pt->pt_time.it_value)) {
   1197 		/* Convert to absolute time */
   1198 		/* XXX need to wrap in splclock for timecounters case? */
   1199 		switch (which) {
   1200 		case ITIMER_REAL:
   1201 			getnanotime(&now);
   1202 			timespecadd(&pt->pt_time.it_value, &now,
   1203 			    &pt->pt_time.it_value);
   1204 			break;
   1205 		case ITIMER_MONOTONIC:
   1206 			getnanouptime(&now);
   1207 			timespecadd(&pt->pt_time.it_value, &now,
   1208 			    &pt->pt_time.it_value);
   1209 			break;
   1210 		default:
   1211 			break;
   1212 		}
   1213 	}
   1214 	timer_settime(pt);
   1215 	mutex_spin_exit(&timer_lock);
   1216 	if (spare != NULL)
   1217 		pool_put(&ptimer_pool, spare);
   1218 
   1219 	return (0);
   1220 }
   1221 
   1222 /* Utility routines to manage the array of pointers to timers. */
   1223 struct ptimers *
   1224 timers_alloc(struct proc *p)
   1225 {
   1226 	struct ptimers *pts;
   1227 	int i;
   1228 
   1229 	pts = pool_get(&ptimers_pool, PR_WAITOK);
   1230 	LIST_INIT(&pts->pts_virtual);
   1231 	LIST_INIT(&pts->pts_prof);
   1232 	for (i = 0; i < TIMER_MAX; i++)
   1233 		pts->pts_timers[i] = NULL;
   1234 	mutex_spin_enter(&timer_lock);
   1235 	if (p->p_timers == NULL) {
   1236 		p->p_timers = pts;
   1237 		mutex_spin_exit(&timer_lock);
   1238 		return pts;
   1239 	}
   1240 	mutex_spin_exit(&timer_lock);
   1241 	pool_put(&ptimers_pool, pts);
   1242 	return p->p_timers;
   1243 }
   1244 
   1245 /*
   1246  * Clean up the per-process timers. If "which" is set to TIMERS_ALL,
   1247  * then clean up all timers and free all the data structures. If
   1248  * "which" is set to TIMERS_POSIX, only clean up the timers allocated
   1249  * by timer_create(), not the BSD setitimer() timers, and only free the
   1250  * structure if none of those remain.
   1251  */
   1252 void
   1253 timers_free(struct proc *p, int which)
   1254 {
   1255 	struct ptimers *pts;
   1256 	struct ptimer *ptn;
   1257 	struct timespec ts;
   1258 	int i;
   1259 
   1260 	if (p->p_timers == NULL)
   1261 		return;
   1262 
   1263 	pts = p->p_timers;
   1264 	mutex_spin_enter(&timer_lock);
   1265 	if (which == TIMERS_ALL) {
   1266 		p->p_timers = NULL;
   1267 		i = 0;
   1268 	} else {
   1269 		timespecclear(&ts);
   1270 		for (ptn = LIST_FIRST(&pts->pts_virtual);
   1271 		     ptn && ptn != pts->pts_timers[ITIMER_VIRTUAL];
   1272 		     ptn = LIST_NEXT(ptn, pt_list)) {
   1273 			KASSERT(ptn->pt_type == CLOCK_VIRTUAL);
   1274 			timespecadd(&ts, &ptn->pt_time.it_value, &ts);
   1275 		}
   1276 		LIST_FIRST(&pts->pts_virtual) = NULL;
   1277 		if (ptn) {
   1278 			KASSERT(ptn->pt_type == CLOCK_VIRTUAL);
   1279 			timespecadd(&ts, &ptn->pt_time.it_value,
   1280 			    &ptn->pt_time.it_value);
   1281 			LIST_INSERT_HEAD(&pts->pts_virtual, ptn, pt_list);
   1282 		}
   1283 		timespecclear(&ts);
   1284 		for (ptn = LIST_FIRST(&pts->pts_prof);
   1285 		     ptn && ptn != pts->pts_timers[ITIMER_PROF];
   1286 		     ptn = LIST_NEXT(ptn, pt_list)) {
   1287 			KASSERT(ptn->pt_type == CLOCK_PROF);
   1288 			timespecadd(&ts, &ptn->pt_time.it_value, &ts);
   1289 		}
   1290 		LIST_FIRST(&pts->pts_prof) = NULL;
   1291 		if (ptn) {
   1292 			KASSERT(ptn->pt_type == CLOCK_PROF);
   1293 			timespecadd(&ts, &ptn->pt_time.it_value,
   1294 			    &ptn->pt_time.it_value);
   1295 			LIST_INSERT_HEAD(&pts->pts_prof, ptn, pt_list);
   1296 		}
   1297 		i = TIMER_MIN;
   1298 	}
   1299 	for ( ; i < TIMER_MAX; i++) {
   1300 		if (pts->pts_timers[i] != NULL) {
   1301 			itimerfree(pts, i);
   1302 			mutex_spin_enter(&timer_lock);
   1303 		}
   1304 	}
   1305 	if (pts->pts_timers[0] == NULL && pts->pts_timers[1] == NULL &&
   1306 	    pts->pts_timers[2] == NULL && pts->pts_timers[3] == NULL) {
   1307 		p->p_timers = NULL;
   1308 		mutex_spin_exit(&timer_lock);
   1309 		pool_put(&ptimers_pool, pts);
   1310 	} else
   1311 		mutex_spin_exit(&timer_lock);
   1312 }
   1313 
   1314 static void
   1315 itimerfree(struct ptimers *pts, int index)
   1316 {
   1317 	struct ptimer *pt;
   1318 
   1319 	KASSERT(mutex_owned(&timer_lock));
   1320 
   1321 	pt = pts->pts_timers[index];
   1322 	pts->pts_timers[index] = NULL;
   1323 	if (!CLOCK_VIRTUAL_P(pt->pt_type))
   1324 		callout_halt(&pt->pt_ch, &timer_lock);
   1325 	if (pt->pt_queued)
   1326 		TAILQ_REMOVE(&timer_queue, pt, pt_chain);
   1327 	mutex_spin_exit(&timer_lock);
   1328 	if (!CLOCK_VIRTUAL_P(pt->pt_type))
   1329 		callout_destroy(&pt->pt_ch);
   1330 	pool_put(&ptimer_pool, pt);
   1331 }
   1332 
   1333 /*
   1334  * Decrement an interval timer by a specified number
   1335  * of nanoseconds, which must be less than a second,
   1336  * i.e. < 1000000000.  If the timer expires, then reload
   1337  * it.  In this case, carry over (nsec - old value) to
   1338  * reduce the value reloaded into the timer so that
   1339  * the timer does not drift.  This routine assumes
   1340  * that it is called in a context where the timers
   1341  * on which it is operating cannot change in value.
   1342  */
   1343 static int
   1344 itimerdecr(struct ptimer *pt, int nsec)
   1345 {
   1346 	struct itimerspec *itp;
   1347 
   1348 	KASSERT(mutex_owned(&timer_lock));
   1349 	KASSERT(CLOCK_VIRTUAL_P(pt->pt_type));
   1350 
   1351 	itp = &pt->pt_time;
   1352 	if (itp->it_value.tv_nsec < nsec) {
   1353 		if (itp->it_value.tv_sec == 0) {
   1354 			/* expired, and already in next interval */
   1355 			nsec -= itp->it_value.tv_nsec;
   1356 			goto expire;
   1357 		}
   1358 		itp->it_value.tv_nsec += 1000000000;
   1359 		itp->it_value.tv_sec--;
   1360 	}
   1361 	itp->it_value.tv_nsec -= nsec;
   1362 	nsec = 0;
   1363 	if (timespecisset(&itp->it_value))
   1364 		return (1);
   1365 	/* expired, exactly at end of interval */
   1366 expire:
   1367 	if (timespecisset(&itp->it_interval)) {
   1368 		itp->it_value = itp->it_interval;
   1369 		itp->it_value.tv_nsec -= nsec;
   1370 		if (itp->it_value.tv_nsec < 0) {
   1371 			itp->it_value.tv_nsec += 1000000000;
   1372 			itp->it_value.tv_sec--;
   1373 		}
   1374 		timer_settime(pt);
   1375 	} else
   1376 		itp->it_value.tv_nsec = 0;		/* sec is already 0 */
   1377 	return (0);
   1378 }
   1379 
   1380 static void
   1381 itimerfire(struct ptimer *pt)
   1382 {
   1383 
   1384 	KASSERT(mutex_owned(&timer_lock));
   1385 
   1386 	/*
   1387 	 * XXX Can overrun, but we don't do signal queueing yet, anyway.
   1388 	 * XXX Relying on the clock interrupt is stupid.
   1389 	 */
   1390 	if (pt->pt_ev.sigev_notify != SIGEV_SIGNAL || pt->pt_queued) {
   1391 		return;
   1392 	}
   1393 	TAILQ_INSERT_TAIL(&timer_queue, pt, pt_chain);
   1394 	pt->pt_queued = true;
   1395 	softint_schedule(timer_sih);
   1396 }
   1397 
   1398 void
   1399 timer_tick(lwp_t *l, bool user)
   1400 {
   1401 	struct ptimers *pts;
   1402 	struct ptimer *pt;
   1403 	proc_t *p;
   1404 
   1405 	p = l->l_proc;
   1406 	if (p->p_timers == NULL)
   1407 		return;
   1408 
   1409 	mutex_spin_enter(&timer_lock);
   1410 	if ((pts = l->l_proc->p_timers) != NULL) {
   1411 		/*
   1412 		 * Run current process's virtual and profile time, as needed.
   1413 		 */
   1414 		if (user && (pt = LIST_FIRST(&pts->pts_virtual)) != NULL)
   1415 			if (itimerdecr(pt, tick * 1000) == 0)
   1416 				itimerfire(pt);
   1417 		if ((pt = LIST_FIRST(&pts->pts_prof)) != NULL)
   1418 			if (itimerdecr(pt, tick * 1000) == 0)
   1419 				itimerfire(pt);
   1420 	}
   1421 	mutex_spin_exit(&timer_lock);
   1422 }
   1423 
   1424 static void
   1425 timer_intr(void *cookie)
   1426 {
   1427 	ksiginfo_t ksi;
   1428 	struct ptimer *pt;
   1429 	proc_t *p;
   1430 
   1431 	mutex_enter(proc_lock);
   1432 	mutex_spin_enter(&timer_lock);
   1433 	while ((pt = TAILQ_FIRST(&timer_queue)) != NULL) {
   1434 		TAILQ_REMOVE(&timer_queue, pt, pt_chain);
   1435 		KASSERT(pt->pt_queued);
   1436 		pt->pt_queued = false;
   1437 
   1438 		if (pt->pt_proc->p_timers == NULL) {
   1439 			/* Process is dying. */
   1440 			continue;
   1441 		}
   1442 		p = pt->pt_proc;
   1443 		if (pt->pt_ev.sigev_notify != SIGEV_SIGNAL) {
   1444 			continue;
   1445 		}
   1446 		if (sigismember(&p->p_sigpend.sp_set, pt->pt_ev.sigev_signo)) {
   1447 			pt->pt_overruns++;
   1448 			continue;
   1449 		}
   1450 
   1451 		KSI_INIT(&ksi);
   1452 		ksi.ksi_signo = pt->pt_ev.sigev_signo;
   1453 		ksi.ksi_code = SI_TIMER;
   1454 		ksi.ksi_value = pt->pt_ev.sigev_value;
   1455 		pt->pt_poverruns = pt->pt_overruns;
   1456 		pt->pt_overruns = 0;
   1457 		mutex_spin_exit(&timer_lock);
   1458 		kpsignal(p, &ksi, NULL);
   1459 		mutex_spin_enter(&timer_lock);
   1460 	}
   1461 	mutex_spin_exit(&timer_lock);
   1462 	mutex_exit(proc_lock);
   1463 }
   1464 
   1465 /*
   1466  * Check if the time will wrap if set to ts.
   1467  *
   1468  * ts - timespec describing the new time
   1469  * delta - the delta between the current time and ts
   1470  */
   1471 bool
   1472 time_wraps(struct timespec *ts, struct timespec *delta)
   1473 {
   1474 
   1475 	/*
   1476 	 * Don't allow the time to be set forward so far it
   1477 	 * will wrap and become negative, thus allowing an
   1478 	 * attacker to bypass the next check below.  The
   1479 	 * cutoff is 1 year before rollover occurs, so even
   1480 	 * if the attacker uses adjtime(2) to move the time
   1481 	 * past the cutoff, it will take a very long time
   1482 	 * to get to the wrap point.
   1483 	 */
   1484 	if ((ts->tv_sec > LLONG_MAX - 365*24*60*60) ||
   1485 	    (delta->tv_sec < 0 || delta->tv_nsec < 0))
   1486 		return true;
   1487 
   1488 	return false;
   1489 }
   1490