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