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