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