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