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