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