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