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