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