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