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