Home | History | Annotate | Line # | Download | only in kern
kern_time.c revision 1.177
      1 /*	$NetBSD: kern_time.c,v 1.177 2013/03/29 10:34:12 martin Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2000, 2004, 2005, 2007, 2008, 2009 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, and by Andrew Doran.
      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  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  * Copyright (c) 1982, 1986, 1989, 1993
     34  *	The Regents of the University of California.  All rights reserved.
     35  *
     36  * Redistribution and use in source and binary forms, with or without
     37  * modification, are permitted provided that the following conditions
     38  * are met:
     39  * 1. Redistributions of source code must retain the above copyright
     40  *    notice, this list of conditions and the following disclaimer.
     41  * 2. Redistributions in binary form must reproduce the above copyright
     42  *    notice, this list of conditions and the following disclaimer in the
     43  *    documentation and/or other materials provided with the distribution.
     44  * 3. Neither the name of the University nor the names of its contributors
     45  *    may be used to endorse or promote products derived from this software
     46  *    without specific prior written permission.
     47  *
     48  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     58  * SUCH DAMAGE.
     59  *
     60  *	@(#)kern_time.c	8.4 (Berkeley) 5/26/95
     61  */
     62 
     63 #include <sys/cdefs.h>
     64 __KERNEL_RCSID(0, "$NetBSD: kern_time.c,v 1.177 2013/03/29 10:34:12 martin Exp $");
     65 
     66 #include <sys/param.h>
     67 #include <sys/resourcevar.h>
     68 #include <sys/kernel.h>
     69 #include <sys/systm.h>
     70 #include <sys/proc.h>
     71 #include <sys/vnode.h>
     72 #include <sys/signalvar.h>
     73 #include <sys/syslog.h>
     74 #include <sys/timetc.h>
     75 #include <sys/timex.h>
     76 #include <sys/kauth.h>
     77 #include <sys/mount.h>
     78 #include <sys/syscallargs.h>
     79 #include <sys/cpu.h>
     80 
     81 static void	timer_intr(void *);
     82 static void	itimerfire(struct ptimer *);
     83 static void	itimerfree(struct ptimers *, int);
     84 
     85 kmutex_t	timer_lock;
     86 
     87 static void	*timer_sih;
     88 static TAILQ_HEAD(, ptimer) timer_queue;
     89 
     90 struct pool ptimer_pool, ptimers_pool;
     91 
     92 #define	CLOCK_VIRTUAL_P(clockid)	\
     93 	((clockid) == CLOCK_VIRTUAL || (clockid) == CLOCK_PROF)
     94 
     95 CTASSERT(ITIMER_REAL == CLOCK_REALTIME);
     96 CTASSERT(ITIMER_VIRTUAL == CLOCK_VIRTUAL);
     97 CTASSERT(ITIMER_PROF == CLOCK_PROF);
     98 CTASSERT(ITIMER_MONOTONIC == CLOCK_MONOTONIC);
     99 
    100 /*
    101  * Initialize timekeeping.
    102  */
    103 void
    104 time_init(void)
    105 {
    106 
    107 	pool_init(&ptimer_pool, sizeof(struct ptimer), 0, 0, 0, "ptimerpl",
    108 	    &pool_allocator_nointr, IPL_NONE);
    109 	pool_init(&ptimers_pool, sizeof(struct ptimers), 0, 0, 0, "ptimerspl",
    110 	    &pool_allocator_nointr, IPL_NONE);
    111 }
    112 
    113 void
    114 time_init2(void)
    115 {
    116 
    117 	TAILQ_INIT(&timer_queue);
    118 	mutex_init(&timer_lock, MUTEX_DEFAULT, IPL_SCHED);
    119 	timer_sih = softint_establish(SOFTINT_CLOCK | SOFTINT_MPSAFE,
    120 	    timer_intr, NULL);
    121 }
    122 
    123 /* Time of day and interval timer support.
    124  *
    125  * These routines provide the kernel entry points to get and set
    126  * the time-of-day and per-process interval timers.  Subroutines
    127  * here provide support for adding and subtracting timeval structures
    128  * and decrementing interval timers, optionally reloading the interval
    129  * timers when they expire.
    130  */
    131 
    132 /* This function is used by clock_settime and settimeofday */
    133 static int
    134 settime1(struct proc *p, const struct timespec *ts, bool check_kauth)
    135 {
    136 	struct timespec delta, now;
    137 	int s;
    138 
    139 	/* WHAT DO WE DO ABOUT PENDING REAL-TIME TIMEOUTS??? */
    140 	s = splclock();
    141 	nanotime(&now);
    142 	timespecsub(ts, &now, &delta);
    143 
    144 	if (check_kauth && kauth_authorize_system(kauth_cred_get(),
    145 	    KAUTH_SYSTEM_TIME, KAUTH_REQ_SYSTEM_TIME_SYSTEM, __UNCONST(ts),
    146 	    &delta, KAUTH_ARG(check_kauth ? false : true)) != 0) {
    147 		splx(s);
    148 		return (EPERM);
    149 	}
    150 
    151 #ifdef notyet
    152 	if ((delta.tv_sec < 86400) && securelevel > 0) { /* XXX elad - notyet */
    153 		splx(s);
    154 		return (EPERM);
    155 	}
    156 #endif
    157 
    158 	tc_setclock(ts);
    159 
    160 	timespecadd(&boottime, &delta, &boottime);
    161 
    162 	resettodr();
    163 	splx(s);
    164 
    165 	return (0);
    166 }
    167 
    168 int
    169 settime(struct proc *p, struct timespec *ts)
    170 {
    171 	return (settime1(p, ts, true));
    172 }
    173 
    174 /* ARGSUSED */
    175 int
    176 sys___clock_gettime50(struct lwp *l,
    177     const struct sys___clock_gettime50_args *uap, register_t *retval)
    178 {
    179 	/* {
    180 		syscallarg(clockid_t) clock_id;
    181 		syscallarg(struct timespec *) tp;
    182 	} */
    183 	int error;
    184 	struct timespec ats;
    185 
    186 	error = clock_gettime1(SCARG(uap, clock_id), &ats);
    187 	if (error != 0)
    188 		return error;
    189 
    190 	return copyout(&ats, SCARG(uap, tp), sizeof(ats));
    191 }
    192 
    193 /* ARGSUSED */
    194 int
    195 sys___clock_settime50(struct lwp *l,
    196     const struct sys___clock_settime50_args *uap, register_t *retval)
    197 {
    198 	/* {
    199 		syscallarg(clockid_t) clock_id;
    200 		syscallarg(const struct timespec *) tp;
    201 	} */
    202 	int error;
    203 	struct timespec ats;
    204 
    205 	if ((error = copyin(SCARG(uap, tp), &ats, sizeof(ats))) != 0)
    206 		return error;
    207 
    208 	return clock_settime1(l->l_proc, SCARG(uap, clock_id), &ats, true);
    209 }
    210 
    211 
    212 int
    213 clock_settime1(struct proc *p, clockid_t clock_id, const struct timespec *tp,
    214     bool check_kauth)
    215 {
    216 	int error;
    217 
    218 	switch (clock_id) {
    219 	case CLOCK_REALTIME:
    220 		if ((error = settime1(p, tp, check_kauth)) != 0)
    221 			return (error);
    222 		break;
    223 	case CLOCK_MONOTONIC:
    224 		return (EINVAL);	/* read-only clock */
    225 	default:
    226 		return (EINVAL);
    227 	}
    228 
    229 	return 0;
    230 }
    231 
    232 int
    233 sys___clock_getres50(struct lwp *l, const struct sys___clock_getres50_args *uap,
    234     register_t *retval)
    235 {
    236 	/* {
    237 		syscallarg(clockid_t) clock_id;
    238 		syscallarg(struct timespec *) tp;
    239 	} */
    240 	struct timespec ts;
    241 	int error = 0;
    242 
    243 	if ((error = clock_getres1(SCARG(uap, clock_id), &ts)) != 0)
    244 		return error;
    245 
    246 	if (SCARG(uap, tp))
    247 		error = copyout(&ts, SCARG(uap, tp), sizeof(ts));
    248 
    249 	return error;
    250 }
    251 
    252 int
    253 clock_getres1(clockid_t clock_id, struct timespec *ts)
    254 {
    255 
    256 	switch (clock_id) {
    257 	case CLOCK_REALTIME:
    258 	case CLOCK_MONOTONIC:
    259 		ts->tv_sec = 0;
    260 		if (tc_getfrequency() > 1000000000)
    261 			ts->tv_nsec = 1;
    262 		else
    263 			ts->tv_nsec = 1000000000 / tc_getfrequency();
    264 		break;
    265 	default:
    266 		return EINVAL;
    267 	}
    268 
    269 	return 0;
    270 }
    271 
    272 /* ARGSUSED */
    273 int
    274 sys___nanosleep50(struct lwp *l, const struct sys___nanosleep50_args *uap,
    275     register_t *retval)
    276 {
    277 	/* {
    278 		syscallarg(struct timespec *) rqtp;
    279 		syscallarg(struct timespec *) rmtp;
    280 	} */
    281 	struct timespec rmt, rqt;
    282 	int error, error1;
    283 
    284 	error = copyin(SCARG(uap, rqtp), &rqt, sizeof(struct timespec));
    285 	if (error)
    286 		return (error);
    287 
    288 	error = nanosleep1(l, CLOCK_MONOTONIC, 0, &rqt,
    289 	    SCARG(uap, rmtp) ? &rmt : NULL);
    290 	if (SCARG(uap, rmtp) == NULL || (error != 0 && error != EINTR))
    291 		return error;
    292 
    293 	error1 = copyout(&rmt, SCARG(uap, rmtp), sizeof(rmt));
    294 	return error1 ? error1 : error;
    295 }
    296 
    297 /* ARGSUSED */
    298 int
    299 sys_clock_nanosleep(struct lwp *l, const struct sys_clock_nanosleep_args *uap,
    300     register_t *retval)
    301 {
    302 	/* {
    303 		syscallarg(clockid_t) clock_id;
    304 		syscallarg(int) flags;
    305 		syscallarg(struct timespec *) rqtp;
    306 		syscallarg(struct timespec *) rmtp;
    307 	} */
    308 	struct timespec rmt, rqt;
    309 	int error, error1;
    310 
    311 	error = copyin(SCARG(uap, rqtp), &rqt, sizeof(struct timespec));
    312 	if (error)
    313 		return (error);
    314 
    315 	error = nanosleep1(l, SCARG(uap, clock_id), SCARG(uap, flags), &rqt,
    316 	    SCARG(uap, rmtp) ? &rmt : NULL);
    317 	if (SCARG(uap, rmtp) == NULL || (error != 0 && error != EINTR))
    318 		return error;
    319 
    320 	error1 = copyout(&rmt, SCARG(uap, rmtp), sizeof(rmt));
    321 	return error1 ? error1 : error;
    322 }
    323 
    324 int
    325 nanosleep1(struct lwp *l, clockid_t clock_id, int flags, struct timespec *rqt,
    326     struct timespec *rmt)
    327 {
    328 	struct timespec rmtstart;
    329 	int error, timo;
    330 
    331 	if ((error = ts2timo(clock_id, flags, rqt, &timo, &rmtstart)) != 0) {
    332 		if (error == ETIMEDOUT)
    333 			timo = 0;
    334 	}
    335 
    336 	/*
    337 	 * Avoid inadvertently sleeping forever
    338 	 */
    339 	if (timo == 0)
    340 		timo = 1;
    341 again:
    342 	error = kpause("nanoslp", true, timo, NULL);
    343 	if (rmt != NULL || error == 0) {
    344 		struct timespec rmtend;
    345 		struct timespec t0;
    346 		struct timespec *t;
    347 
    348 		(void)clock_gettime1(clock_id, &rmtend);
    349 		t = (rmt != NULL) ? rmt : &t0;
    350 		timespecsub(&rmtend, &rmtstart, t);
    351 		timespecsub(rqt, t, t);
    352 		if (t->tv_sec < 0)
    353 			timespecclear(t);
    354 		if (error == 0) {
    355 			timo = tstohz(t);
    356 			if (timo > 0)
    357 				goto again;
    358 		}
    359 	}
    360 
    361 	if (error == ERESTART)
    362 		error = EINTR;
    363 	if (error == EWOULDBLOCK)
    364 		error = 0;
    365 
    366 	return error;
    367 }
    368 
    369 /* ARGSUSED */
    370 int
    371 sys___gettimeofday50(struct lwp *l, const struct sys___gettimeofday50_args *uap,
    372     register_t *retval)
    373 {
    374 	/* {
    375 		syscallarg(struct timeval *) tp;
    376 		syscallarg(void *) tzp;		really "struct timezone *";
    377 	} */
    378 	struct timeval atv;
    379 	int error = 0;
    380 	struct timezone tzfake;
    381 
    382 	if (SCARG(uap, tp)) {
    383 		microtime(&atv);
    384 		error = copyout(&atv, SCARG(uap, tp), sizeof(atv));
    385 		if (error)
    386 			return (error);
    387 	}
    388 	if (SCARG(uap, tzp)) {
    389 		/*
    390 		 * NetBSD has no kernel notion of time zone, so we just
    391 		 * fake up a timezone struct and return it if demanded.
    392 		 */
    393 		tzfake.tz_minuteswest = 0;
    394 		tzfake.tz_dsttime = 0;
    395 		error = copyout(&tzfake, SCARG(uap, tzp), sizeof(tzfake));
    396 	}
    397 	return (error);
    398 }
    399 
    400 /* ARGSUSED */
    401 int
    402 sys___settimeofday50(struct lwp *l, const struct sys___settimeofday50_args *uap,
    403     register_t *retval)
    404 {
    405 	/* {
    406 		syscallarg(const struct timeval *) tv;
    407 		syscallarg(const void *) tzp; really "const struct timezone *";
    408 	} */
    409 
    410 	return settimeofday1(SCARG(uap, tv), true, SCARG(uap, tzp), l, true);
    411 }
    412 
    413 int
    414 settimeofday1(const struct timeval *utv, bool userspace,
    415     const void *utzp, struct lwp *l, bool check_kauth)
    416 {
    417 	struct timeval atv;
    418 	struct timespec ts;
    419 	int error;
    420 
    421 	/* Verify all parameters before changing time. */
    422 
    423 	/*
    424 	 * NetBSD has no kernel notion of time zone, and only an
    425 	 * obsolete program would try to set it, so we log a warning.
    426 	 */
    427 	if (utzp)
    428 		log(LOG_WARNING, "pid %d attempted to set the "
    429 		    "(obsolete) kernel time zone\n", l->l_proc->p_pid);
    430 
    431 	if (utv == NULL)
    432 		return 0;
    433 
    434 	if (userspace) {
    435 		if ((error = copyin(utv, &atv, sizeof(atv))) != 0)
    436 			return error;
    437 		utv = &atv;
    438 	}
    439 
    440 	TIMEVAL_TO_TIMESPEC(utv, &ts);
    441 	return settime1(l->l_proc, &ts, check_kauth);
    442 }
    443 
    444 int	time_adjusted;			/* set if an adjustment is made */
    445 
    446 /* ARGSUSED */
    447 int
    448 sys___adjtime50(struct lwp *l, const struct sys___adjtime50_args *uap,
    449     register_t *retval)
    450 {
    451 	/* {
    452 		syscallarg(const struct timeval *) delta;
    453 		syscallarg(struct timeval *) olddelta;
    454 	} */
    455 	int error = 0;
    456 	struct timeval atv, oldatv;
    457 
    458 	if ((error = kauth_authorize_system(l->l_cred, KAUTH_SYSTEM_TIME,
    459 	    KAUTH_REQ_SYSTEM_TIME_ADJTIME, NULL, NULL, NULL)) != 0)
    460 		return error;
    461 
    462 	if (SCARG(uap, delta)) {
    463 		error = copyin(SCARG(uap, delta), &atv,
    464 		    sizeof(*SCARG(uap, delta)));
    465 		if (error)
    466 			return (error);
    467 	}
    468 	adjtime1(SCARG(uap, delta) ? &atv : NULL,
    469 	    SCARG(uap, olddelta) ? &oldatv : NULL, l->l_proc);
    470 	if (SCARG(uap, olddelta))
    471 		error = copyout(&oldatv, SCARG(uap, olddelta),
    472 		    sizeof(*SCARG(uap, olddelta)));
    473 	return error;
    474 }
    475 
    476 void
    477 adjtime1(const struct timeval *delta, struct timeval *olddelta, struct proc *p)
    478 {
    479 	extern int64_t time_adjtime;  /* in kern_ntptime.c */
    480 
    481 	if (olddelta) {
    482 		mutex_spin_enter(&timecounter_lock);
    483 		olddelta->tv_sec = time_adjtime / 1000000;
    484 		olddelta->tv_usec = time_adjtime % 1000000;
    485 		if (olddelta->tv_usec < 0) {
    486 			olddelta->tv_usec += 1000000;
    487 			olddelta->tv_sec--;
    488 		}
    489 		mutex_spin_exit(&timecounter_lock);
    490 	}
    491 
    492 	if (delta) {
    493 		mutex_spin_enter(&timecounter_lock);
    494 		time_adjtime = delta->tv_sec * 1000000 + delta->tv_usec;
    495 
    496 		if (time_adjtime) {
    497 			/* We need to save the system time during shutdown */
    498 			time_adjusted |= 1;
    499 		}
    500 		mutex_spin_exit(&timecounter_lock);
    501 	}
    502 }
    503 
    504 /*
    505  * Interval timer support. Both the BSD getitimer() family and the POSIX
    506  * timer_*() family of routines are supported.
    507  *
    508  * All timers are kept in an array pointed to by p_timers, which is
    509  * allocated on demand - many processes don't use timers at all. The
    510  * first three elements in this array are reserved for the BSD timers:
    511  * element 0 is ITIMER_REAL, element 1 is ITIMER_VIRTUAL, element
    512  * 2 is ITIMER_PROF, and element 3 is ITIMER_MONOTONIC. The rest may be
    513  * allocated by the timer_create() syscall.
    514  *
    515  * Realtime timers are kept in the ptimer structure as an absolute
    516  * time; virtual time timers are kept as a linked list of deltas.
    517  * Virtual time timers are processed in the hardclock() routine of
    518  * kern_clock.c.  The real time timer is processed by a callout
    519  * routine, called from the softclock() routine.  Since a callout may
    520  * be delayed in real time due to interrupt processing in the system,
    521  * it is possible for the real time timeout routine (realtimeexpire,
    522  * given below), to be delayed in real time past when it is supposed
    523  * to occur.  It does not suffice, therefore, to reload the real timer
    524  * .it_value from the real time timers .it_interval.  Rather, we
    525  * compute the next time in absolute time the timer should go off.  */
    526 
    527 /* Allocate a POSIX realtime timer. */
    528 int
    529 sys_timer_create(struct lwp *l, const struct sys_timer_create_args *uap,
    530     register_t *retval)
    531 {
    532 	/* {
    533 		syscallarg(clockid_t) clock_id;
    534 		syscallarg(struct sigevent *) evp;
    535 		syscallarg(timer_t *) timerid;
    536 	} */
    537 
    538 	return timer_create1(SCARG(uap, timerid), SCARG(uap, clock_id),
    539 	    SCARG(uap, evp), copyin, l);
    540 }
    541 
    542 int
    543 timer_create1(timer_t *tid, clockid_t id, struct sigevent *evp,
    544     copyin_t fetch_event, struct lwp *l)
    545 {
    546 	int error;
    547 	timer_t timerid;
    548 	struct ptimers *pts;
    549 	struct ptimer *pt;
    550 	struct proc *p;
    551 
    552 	p = l->l_proc;
    553 
    554 	if ((u_int)id > CLOCK_MONOTONIC)
    555 		return (EINVAL);
    556 
    557 	if ((pts = p->p_timers) == NULL)
    558 		pts = timers_alloc(p);
    559 
    560 	pt = pool_get(&ptimer_pool, PR_WAITOK);
    561 	if (evp != NULL) {
    562 		if (((error =
    563 		    (*fetch_event)(evp, &pt->pt_ev, sizeof(pt->pt_ev))) != 0) ||
    564 		    ((pt->pt_ev.sigev_notify < SIGEV_NONE) ||
    565 			(pt->pt_ev.sigev_notify > SIGEV_SA)) ||
    566 			(pt->pt_ev.sigev_notify == SIGEV_SIGNAL &&
    567 			 (pt->pt_ev.sigev_signo <= 0 ||
    568 			  pt->pt_ev.sigev_signo >= NSIG))) {
    569 			pool_put(&ptimer_pool, pt);
    570 			return (error ? error : EINVAL);
    571 		}
    572 	}
    573 
    574 	/* Find a free timer slot, skipping those reserved for setitimer(). */
    575 	mutex_spin_enter(&timer_lock);
    576 	for (timerid = 3; timerid < TIMER_MAX; timerid++)
    577 		if (pts->pts_timers[timerid] == NULL)
    578 			break;
    579 	if (timerid == TIMER_MAX) {
    580 		mutex_spin_exit(&timer_lock);
    581 		pool_put(&ptimer_pool, pt);
    582 		return EAGAIN;
    583 	}
    584 	if (evp == NULL) {
    585 		pt->pt_ev.sigev_notify = SIGEV_SIGNAL;
    586 		switch (id) {
    587 		case CLOCK_REALTIME:
    588 		case CLOCK_MONOTONIC:
    589 			pt->pt_ev.sigev_signo = SIGALRM;
    590 			break;
    591 		case CLOCK_VIRTUAL:
    592 			pt->pt_ev.sigev_signo = SIGVTALRM;
    593 			break;
    594 		case CLOCK_PROF:
    595 			pt->pt_ev.sigev_signo = SIGPROF;
    596 			break;
    597 		}
    598 		pt->pt_ev.sigev_value.sival_int = timerid;
    599 	}
    600 	pt->pt_info.ksi_signo = pt->pt_ev.sigev_signo;
    601 	pt->pt_info.ksi_errno = 0;
    602 	pt->pt_info.ksi_code = 0;
    603 	pt->pt_info.ksi_pid = p->p_pid;
    604 	pt->pt_info.ksi_uid = kauth_cred_getuid(l->l_cred);
    605 	pt->pt_info.ksi_value = pt->pt_ev.sigev_value;
    606 	pt->pt_type = id;
    607 	pt->pt_proc = p;
    608 	pt->pt_overruns = 0;
    609 	pt->pt_poverruns = 0;
    610 	pt->pt_entry = timerid;
    611 	pt->pt_queued = false;
    612 	timespecclear(&pt->pt_time.it_value);
    613 	if (!CLOCK_VIRTUAL_P(id))
    614 		callout_init(&pt->pt_ch, CALLOUT_MPSAFE);
    615 	else
    616 		pt->pt_active = 0;
    617 
    618 	pts->pts_timers[timerid] = pt;
    619 	mutex_spin_exit(&timer_lock);
    620 
    621 	return copyout(&timerid, tid, sizeof(timerid));
    622 }
    623 
    624 /* Delete a POSIX realtime timer */
    625 int
    626 sys_timer_delete(struct lwp *l, const struct sys_timer_delete_args *uap,
    627     register_t *retval)
    628 {
    629 	/* {
    630 		syscallarg(timer_t) timerid;
    631 	} */
    632 	struct proc *p = l->l_proc;
    633 	timer_t timerid;
    634 	struct ptimers *pts;
    635 	struct ptimer *pt, *ptn;
    636 
    637 	timerid = SCARG(uap, timerid);
    638 	pts = p->p_timers;
    639 
    640 	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
    641 		return (EINVAL);
    642 
    643 	mutex_spin_enter(&timer_lock);
    644 	if ((pt = pts->pts_timers[timerid]) == NULL) {
    645 		mutex_spin_exit(&timer_lock);
    646 		return (EINVAL);
    647 	}
    648 	if (CLOCK_VIRTUAL_P(pt->pt_type)) {
    649 		if (pt->pt_active) {
    650 			ptn = LIST_NEXT(pt, pt_list);
    651 			LIST_REMOVE(pt, pt_list);
    652 			for ( ; ptn; ptn = LIST_NEXT(ptn, pt_list))
    653 				timespecadd(&pt->pt_time.it_value,
    654 				    &ptn->pt_time.it_value,
    655 				    &ptn->pt_time.it_value);
    656 			pt->pt_active = 0;
    657 		}
    658 	}
    659 	itimerfree(pts, timerid);
    660 
    661 	return (0);
    662 }
    663 
    664 /*
    665  * Set up the given timer. The value in pt->pt_time.it_value is taken
    666  * to be an absolute time for CLOCK_REALTIME/CLOCK_MONOTONIC timers and
    667  * a relative time for CLOCK_VIRTUAL/CLOCK_PROF timers.
    668  */
    669 void
    670 timer_settime(struct ptimer *pt)
    671 {
    672 	struct ptimer *ptn, *pptn;
    673 	struct ptlist *ptl;
    674 
    675 	KASSERT(mutex_owned(&timer_lock));
    676 
    677 	if (!CLOCK_VIRTUAL_P(pt->pt_type)) {
    678 		callout_halt(&pt->pt_ch, &timer_lock);
    679 		if (timespecisset(&pt->pt_time.it_value)) {
    680 			/*
    681 			 * Don't need to check tshzto() return value, here.
    682 			 * callout_reset() does it for us.
    683 			 */
    684 			callout_reset(&pt->pt_ch,
    685 			    pt->pt_type == CLOCK_MONOTONIC ?
    686 			    tshztoup(&pt->pt_time.it_value) :
    687 			    tshzto(&pt->pt_time.it_value),
    688 			    realtimerexpire, pt);
    689 		}
    690 	} else {
    691 		if (pt->pt_active) {
    692 			ptn = LIST_NEXT(pt, pt_list);
    693 			LIST_REMOVE(pt, pt_list);
    694 			for ( ; ptn; ptn = LIST_NEXT(ptn, pt_list))
    695 				timespecadd(&pt->pt_time.it_value,
    696 				    &ptn->pt_time.it_value,
    697 				    &ptn->pt_time.it_value);
    698 		}
    699 		if (timespecisset(&pt->pt_time.it_value)) {
    700 			if (pt->pt_type == CLOCK_VIRTUAL)
    701 				ptl = &pt->pt_proc->p_timers->pts_virtual;
    702 			else
    703 				ptl = &pt->pt_proc->p_timers->pts_prof;
    704 
    705 			for (ptn = LIST_FIRST(ptl), pptn = NULL;
    706 			     ptn && timespeccmp(&pt->pt_time.it_value,
    707 				 &ptn->pt_time.it_value, >);
    708 			     pptn = ptn, ptn = LIST_NEXT(ptn, pt_list))
    709 				timespecsub(&pt->pt_time.it_value,
    710 				    &ptn->pt_time.it_value,
    711 				    &pt->pt_time.it_value);
    712 
    713 			if (pptn)
    714 				LIST_INSERT_AFTER(pptn, pt, pt_list);
    715 			else
    716 				LIST_INSERT_HEAD(ptl, pt, pt_list);
    717 
    718 			for ( ; ptn ; ptn = LIST_NEXT(ptn, pt_list))
    719 				timespecsub(&ptn->pt_time.it_value,
    720 				    &pt->pt_time.it_value,
    721 				    &ptn->pt_time.it_value);
    722 
    723 			pt->pt_active = 1;
    724 		} else
    725 			pt->pt_active = 0;
    726 	}
    727 }
    728 
    729 void
    730 timer_gettime(struct ptimer *pt, struct itimerspec *aits)
    731 {
    732 	struct timespec now;
    733 	struct ptimer *ptn;
    734 
    735 	KASSERT(mutex_owned(&timer_lock));
    736 
    737 	*aits = pt->pt_time;
    738 	if (!CLOCK_VIRTUAL_P(pt->pt_type)) {
    739 		/*
    740 		 * Convert from absolute to relative time in .it_value
    741 		 * part of real time timer.  If time for real time
    742 		 * timer has passed return 0, else return difference
    743 		 * between current time and time for the timer to go
    744 		 * off.
    745 		 */
    746 		if (timespecisset(&aits->it_value)) {
    747 			if (pt->pt_type == CLOCK_REALTIME) {
    748 				getnanotime(&now);
    749 			} else { /* CLOCK_MONOTONIC */
    750 				getnanouptime(&now);
    751 			}
    752 			if (timespeccmp(&aits->it_value, &now, <))
    753 				timespecclear(&aits->it_value);
    754 			else
    755 				timespecsub(&aits->it_value, &now,
    756 				    &aits->it_value);
    757 		}
    758 	} else if (pt->pt_active) {
    759 		if (pt->pt_type == CLOCK_VIRTUAL)
    760 			ptn = LIST_FIRST(&pt->pt_proc->p_timers->pts_virtual);
    761 		else
    762 			ptn = LIST_FIRST(&pt->pt_proc->p_timers->pts_prof);
    763 		for ( ; ptn && ptn != pt; ptn = LIST_NEXT(ptn, pt_list))
    764 			timespecadd(&aits->it_value,
    765 			    &ptn->pt_time.it_value, &aits->it_value);
    766 		KASSERT(ptn != NULL); /* pt should be findable on the list */
    767 	} else
    768 		timespecclear(&aits->it_value);
    769 }
    770 
    771 
    772 
    773 /* Set and arm a POSIX realtime timer */
    774 int
    775 sys___timer_settime50(struct lwp *l,
    776     const struct sys___timer_settime50_args *uap,
    777     register_t *retval)
    778 {
    779 	/* {
    780 		syscallarg(timer_t) timerid;
    781 		syscallarg(int) flags;
    782 		syscallarg(const struct itimerspec *) value;
    783 		syscallarg(struct itimerspec *) ovalue;
    784 	} */
    785 	int error;
    786 	struct itimerspec value, ovalue, *ovp = NULL;
    787 
    788 	if ((error = copyin(SCARG(uap, value), &value,
    789 	    sizeof(struct itimerspec))) != 0)
    790 		return (error);
    791 
    792 	if (SCARG(uap, ovalue))
    793 		ovp = &ovalue;
    794 
    795 	if ((error = dotimer_settime(SCARG(uap, timerid), &value, ovp,
    796 	    SCARG(uap, flags), l->l_proc)) != 0)
    797 		return error;
    798 
    799 	if (ovp)
    800 		return copyout(&ovalue, SCARG(uap, ovalue),
    801 		    sizeof(struct itimerspec));
    802 	return 0;
    803 }
    804 
    805 int
    806 dotimer_settime(int timerid, struct itimerspec *value,
    807     struct itimerspec *ovalue, int flags, struct proc *p)
    808 {
    809 	struct timespec now;
    810 	struct itimerspec val, oval;
    811 	struct ptimers *pts;
    812 	struct ptimer *pt;
    813 	int error;
    814 
    815 	pts = p->p_timers;
    816 
    817 	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
    818 		return EINVAL;
    819 	val = *value;
    820 	if ((error = itimespecfix(&val.it_value)) != 0 ||
    821 	    (error = itimespecfix(&val.it_interval)) != 0)
    822 		return error;
    823 
    824 	mutex_spin_enter(&timer_lock);
    825 	if ((pt = pts->pts_timers[timerid]) == NULL) {
    826 		mutex_spin_exit(&timer_lock);
    827 		return EINVAL;
    828 	}
    829 
    830 	oval = pt->pt_time;
    831 	pt->pt_time = val;
    832 
    833 	/*
    834 	 * If we've been passed a relative time for a realtime timer,
    835 	 * convert it to absolute; if an absolute time for a virtual
    836 	 * timer, convert it to relative and make sure we don't set it
    837 	 * to zero, which would cancel the timer, or let it go
    838 	 * negative, which would confuse the comparison tests.
    839 	 */
    840 	if (timespecisset(&pt->pt_time.it_value)) {
    841 		if (!CLOCK_VIRTUAL_P(pt->pt_type)) {
    842 			if ((flags & TIMER_ABSTIME) == 0) {
    843 				if (pt->pt_type == CLOCK_REALTIME) {
    844 					getnanotime(&now);
    845 				} else { /* CLOCK_MONOTONIC */
    846 					getnanouptime(&now);
    847 				}
    848 				timespecadd(&pt->pt_time.it_value, &now,
    849 				    &pt->pt_time.it_value);
    850 			}
    851 		} else {
    852 			if ((flags & TIMER_ABSTIME) != 0) {
    853 				getnanotime(&now);
    854 				timespecsub(&pt->pt_time.it_value, &now,
    855 				    &pt->pt_time.it_value);
    856 				if (!timespecisset(&pt->pt_time.it_value) ||
    857 				    pt->pt_time.it_value.tv_sec < 0) {
    858 					pt->pt_time.it_value.tv_sec = 0;
    859 					pt->pt_time.it_value.tv_nsec = 1;
    860 				}
    861 			}
    862 		}
    863 	}
    864 
    865 	timer_settime(pt);
    866 	mutex_spin_exit(&timer_lock);
    867 
    868 	if (ovalue)
    869 		*ovalue = oval;
    870 
    871 	return (0);
    872 }
    873 
    874 /* Return the time remaining until a POSIX timer fires. */
    875 int
    876 sys___timer_gettime50(struct lwp *l,
    877     const struct sys___timer_gettime50_args *uap, register_t *retval)
    878 {
    879 	/* {
    880 		syscallarg(timer_t) timerid;
    881 		syscallarg(struct itimerspec *) value;
    882 	} */
    883 	struct itimerspec its;
    884 	int error;
    885 
    886 	if ((error = dotimer_gettime(SCARG(uap, timerid), l->l_proc,
    887 	    &its)) != 0)
    888 		return error;
    889 
    890 	return copyout(&its, SCARG(uap, value), sizeof(its));
    891 }
    892 
    893 int
    894 dotimer_gettime(int timerid, struct proc *p, struct itimerspec *its)
    895 {
    896 	struct ptimer *pt;
    897 	struct ptimers *pts;
    898 
    899 	pts = p->p_timers;
    900 	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
    901 		return (EINVAL);
    902 	mutex_spin_enter(&timer_lock);
    903 	if ((pt = pts->pts_timers[timerid]) == NULL) {
    904 		mutex_spin_exit(&timer_lock);
    905 		return (EINVAL);
    906 	}
    907 	timer_gettime(pt, its);
    908 	mutex_spin_exit(&timer_lock);
    909 
    910 	return 0;
    911 }
    912 
    913 /*
    914  * Return the count of the number of times a periodic timer expired
    915  * while a notification was already pending. The counter is reset when
    916  * a timer expires and a notification can be posted.
    917  */
    918 int
    919 sys_timer_getoverrun(struct lwp *l, const struct sys_timer_getoverrun_args *uap,
    920     register_t *retval)
    921 {
    922 	/* {
    923 		syscallarg(timer_t) timerid;
    924 	} */
    925 	struct proc *p = l->l_proc;
    926 	struct ptimers *pts;
    927 	int timerid;
    928 	struct ptimer *pt;
    929 
    930 	timerid = SCARG(uap, timerid);
    931 
    932 	pts = p->p_timers;
    933 	if (pts == NULL || timerid < 2 || timerid >= TIMER_MAX)
    934 		return (EINVAL);
    935 	mutex_spin_enter(&timer_lock);
    936 	if ((pt = pts->pts_timers[timerid]) == NULL) {
    937 		mutex_spin_exit(&timer_lock);
    938 		return (EINVAL);
    939 	}
    940 	*retval = pt->pt_poverruns;
    941 	mutex_spin_exit(&timer_lock);
    942 
    943 	return (0);
    944 }
    945 
    946 /*
    947  * Real interval timer expired:
    948  * send process whose timer expired an alarm signal.
    949  * If time is not set up to reload, then just return.
    950  * Else compute next time timer should go off which is > current time.
    951  * This is where delay in processing this timeout causes multiple
    952  * SIGALRM calls to be compressed into one.
    953  */
    954 void
    955 realtimerexpire(void *arg)
    956 {
    957 	uint64_t last_val, next_val, interval, now_ns;
    958 	struct timespec now, next;
    959 	struct ptimer *pt;
    960 	int backwards;
    961 
    962 	pt = arg;
    963 
    964 	mutex_spin_enter(&timer_lock);
    965 	itimerfire(pt);
    966 
    967 	if (!timespecisset(&pt->pt_time.it_interval)) {
    968 		timespecclear(&pt->pt_time.it_value);
    969 		mutex_spin_exit(&timer_lock);
    970 		return;
    971 	}
    972 
    973 	if (pt->pt_type == CLOCK_MONOTONIC) {
    974 		getnanouptime(&now);
    975 	} else {
    976 		getnanotime(&now);
    977 	}
    978 	backwards = (timespeccmp(&pt->pt_time.it_value, &now, >));
    979 	timespecadd(&pt->pt_time.it_value, &pt->pt_time.it_interval, &next);
    980 	/* Handle the easy case of non-overflown timers first. */
    981 	if (!backwards && timespeccmp(&next, &now, >)) {
    982 		pt->pt_time.it_value = next;
    983 	} else {
    984 		now_ns = timespec2ns(&now);
    985 		last_val = timespec2ns(&pt->pt_time.it_value);
    986 		interval = timespec2ns(&pt->pt_time.it_interval);
    987 
    988 		next_val = now_ns +
    989 		    (now_ns - last_val + interval - 1) % interval;
    990 
    991 		if (backwards)
    992 			next_val += interval;
    993 		else
    994 			pt->pt_overruns += (now_ns - last_val) / interval;
    995 
    996 		pt->pt_time.it_value.tv_sec = next_val / 1000000000;
    997 		pt->pt_time.it_value.tv_nsec = next_val % 1000000000;
    998 	}
    999 
   1000 	/*
   1001 	 * Don't need to check tshzto() return value, here.
   1002 	 * callout_reset() does it for us.
   1003 	 */
   1004 	callout_reset(&pt->pt_ch, pt->pt_type == CLOCK_MONOTONIC ?
   1005 	    tshztoup(&pt->pt_time.it_value) : tshzto(&pt->pt_time.it_value),
   1006 	    realtimerexpire, pt);
   1007 	mutex_spin_exit(&timer_lock);
   1008 }
   1009 
   1010 /* BSD routine to get the value of an interval timer. */
   1011 /* ARGSUSED */
   1012 int
   1013 sys___getitimer50(struct lwp *l, const struct sys___getitimer50_args *uap,
   1014     register_t *retval)
   1015 {
   1016 	/* {
   1017 		syscallarg(int) which;
   1018 		syscallarg(struct itimerval *) itv;
   1019 	} */
   1020 	struct proc *p = l->l_proc;
   1021 	struct itimerval aitv;
   1022 	int error;
   1023 
   1024 	error = dogetitimer(p, SCARG(uap, which), &aitv);
   1025 	if (error)
   1026 		return error;
   1027 	return (copyout(&aitv, SCARG(uap, itv), sizeof(struct itimerval)));
   1028 }
   1029 
   1030 int
   1031 dogetitimer(struct proc *p, int which, struct itimerval *itvp)
   1032 {
   1033 	struct ptimers *pts;
   1034 	struct ptimer *pt;
   1035 	struct itimerspec its;
   1036 
   1037 	if ((u_int)which > ITIMER_MONOTONIC)
   1038 		return (EINVAL);
   1039 
   1040 	mutex_spin_enter(&timer_lock);
   1041 	pts = p->p_timers;
   1042 	if (pts == NULL || (pt = pts->pts_timers[which]) == NULL) {
   1043 		timerclear(&itvp->it_value);
   1044 		timerclear(&itvp->it_interval);
   1045 	} else {
   1046 		timer_gettime(pt, &its);
   1047 		TIMESPEC_TO_TIMEVAL(&itvp->it_value, &its.it_value);
   1048 		TIMESPEC_TO_TIMEVAL(&itvp->it_interval, &its.it_interval);
   1049 	}
   1050 	mutex_spin_exit(&timer_lock);
   1051 
   1052 	return 0;
   1053 }
   1054 
   1055 /* BSD routine to set/arm an interval timer. */
   1056 /* ARGSUSED */
   1057 int
   1058 sys___setitimer50(struct lwp *l, const struct sys___setitimer50_args *uap,
   1059     register_t *retval)
   1060 {
   1061 	/* {
   1062 		syscallarg(int) which;
   1063 		syscallarg(const struct itimerval *) itv;
   1064 		syscallarg(struct itimerval *) oitv;
   1065 	} */
   1066 	struct proc *p = l->l_proc;
   1067 	int which = SCARG(uap, which);
   1068 	struct sys___getitimer50_args getargs;
   1069 	const struct itimerval *itvp;
   1070 	struct itimerval aitv;
   1071 	int error;
   1072 
   1073 	if ((u_int)which > ITIMER_MONOTONIC)
   1074 		return (EINVAL);
   1075 	itvp = SCARG(uap, itv);
   1076 	if (itvp &&
   1077 	    (error = copyin(itvp, &aitv, sizeof(struct itimerval))) != 0)
   1078 		return (error);
   1079 	if (SCARG(uap, oitv) != NULL) {
   1080 		SCARG(&getargs, which) = which;
   1081 		SCARG(&getargs, itv) = SCARG(uap, oitv);
   1082 		if ((error = sys___getitimer50(l, &getargs, retval)) != 0)
   1083 			return (error);
   1084 	}
   1085 	if (itvp == 0)
   1086 		return (0);
   1087 
   1088 	return dosetitimer(p, which, &aitv);
   1089 }
   1090 
   1091 int
   1092 dosetitimer(struct proc *p, int which, struct itimerval *itvp)
   1093 {
   1094 	struct timespec now;
   1095 	struct ptimers *pts;
   1096 	struct ptimer *pt, *spare;
   1097 
   1098 	KASSERT((u_int)which <= CLOCK_MONOTONIC);
   1099 	if (itimerfix(&itvp->it_value) || itimerfix(&itvp->it_interval))
   1100 		return (EINVAL);
   1101 
   1102 	/*
   1103 	 * Don't bother allocating data structures if the process just
   1104 	 * wants to clear the timer.
   1105 	 */
   1106 	spare = NULL;
   1107 	pts = p->p_timers;
   1108  retry:
   1109 	if (!timerisset(&itvp->it_value) && (pts == NULL ||
   1110 	    pts->pts_timers[which] == NULL))
   1111 		return (0);
   1112 	if (pts == NULL)
   1113 		pts = timers_alloc(p);
   1114 	mutex_spin_enter(&timer_lock);
   1115 	pt = pts->pts_timers[which];
   1116 	if (pt == NULL) {
   1117 		if (spare == NULL) {
   1118 			mutex_spin_exit(&timer_lock);
   1119 			spare = pool_get(&ptimer_pool, PR_WAITOK);
   1120 			goto retry;
   1121 		}
   1122 		pt = spare;
   1123 		spare = NULL;
   1124 		pt->pt_ev.sigev_notify = SIGEV_SIGNAL;
   1125 		pt->pt_ev.sigev_value.sival_int = which;
   1126 		pt->pt_overruns = 0;
   1127 		pt->pt_proc = p;
   1128 		pt->pt_type = which;
   1129 		pt->pt_entry = which;
   1130 		pt->pt_queued = false;
   1131 		if (pt->pt_type == CLOCK_REALTIME)
   1132 			callout_init(&pt->pt_ch, CALLOUT_MPSAFE);
   1133 		else
   1134 			pt->pt_active = 0;
   1135 
   1136 		switch (which) {
   1137 		case ITIMER_REAL:
   1138 		case ITIMER_MONOTONIC:
   1139 			pt->pt_ev.sigev_signo = SIGALRM;
   1140 			break;
   1141 		case ITIMER_VIRTUAL:
   1142 			pt->pt_ev.sigev_signo = SIGVTALRM;
   1143 			break;
   1144 		case ITIMER_PROF:
   1145 			pt->pt_ev.sigev_signo = SIGPROF;
   1146 			break;
   1147 		}
   1148 		pts->pts_timers[which] = pt;
   1149 	}
   1150 
   1151 	TIMEVAL_TO_TIMESPEC(&itvp->it_value, &pt->pt_time.it_value);
   1152 	TIMEVAL_TO_TIMESPEC(&itvp->it_interval, &pt->pt_time.it_interval);
   1153 
   1154 	if (timespecisset(&pt->pt_time.it_value)) {
   1155 		/* Convert to absolute time */
   1156 		/* XXX need to wrap in splclock for timecounters case? */
   1157 		switch (which) {
   1158 		case ITIMER_REAL:
   1159 			getnanotime(&now);
   1160 			timespecadd(&pt->pt_time.it_value, &now,
   1161 			    &pt->pt_time.it_value);
   1162 			break;
   1163 		case ITIMER_MONOTONIC:
   1164 			getnanouptime(&now);
   1165 			timespecadd(&pt->pt_time.it_value, &now,
   1166 			    &pt->pt_time.it_value);
   1167 			break;
   1168 		default:
   1169 			break;
   1170 		}
   1171 	}
   1172 	timer_settime(pt);
   1173 	mutex_spin_exit(&timer_lock);
   1174 	if (spare != NULL)
   1175 		pool_put(&ptimer_pool, spare);
   1176 
   1177 	return (0);
   1178 }
   1179 
   1180 /* Utility routines to manage the array of pointers to timers. */
   1181 struct ptimers *
   1182 timers_alloc(struct proc *p)
   1183 {
   1184 	struct ptimers *pts;
   1185 	int i;
   1186 
   1187 	pts = pool_get(&ptimers_pool, PR_WAITOK);
   1188 	LIST_INIT(&pts->pts_virtual);
   1189 	LIST_INIT(&pts->pts_prof);
   1190 	for (i = 0; i < TIMER_MAX; i++)
   1191 		pts->pts_timers[i] = NULL;
   1192 	pts->pts_fired = 0;
   1193 	mutex_spin_enter(&timer_lock);
   1194 	if (p->p_timers == NULL) {
   1195 		p->p_timers = pts;
   1196 		mutex_spin_exit(&timer_lock);
   1197 		return pts;
   1198 	}
   1199 	mutex_spin_exit(&timer_lock);
   1200 	pool_put(&ptimers_pool, pts);
   1201 	return p->p_timers;
   1202 }
   1203 
   1204 /*
   1205  * Clean up the per-process timers. If "which" is set to TIMERS_ALL,
   1206  * then clean up all timers and free all the data structures. If
   1207  * "which" is set to TIMERS_POSIX, only clean up the timers allocated
   1208  * by timer_create(), not the BSD setitimer() timers, and only free the
   1209  * structure if none of those remain.
   1210  */
   1211 void
   1212 timers_free(struct proc *p, int which)
   1213 {
   1214 	struct ptimers *pts;
   1215 	struct ptimer *ptn;
   1216 	struct timespec ts;
   1217 	int i;
   1218 
   1219 	if (p->p_timers == NULL)
   1220 		return;
   1221 
   1222 	pts = p->p_timers;
   1223 	mutex_spin_enter(&timer_lock);
   1224 	if (which == TIMERS_ALL) {
   1225 		p->p_timers = NULL;
   1226 		i = 0;
   1227 	} else {
   1228 		timespecclear(&ts);
   1229 		for (ptn = LIST_FIRST(&pts->pts_virtual);
   1230 		     ptn && ptn != pts->pts_timers[ITIMER_VIRTUAL];
   1231 		     ptn = LIST_NEXT(ptn, pt_list)) {
   1232 			KASSERT(ptn->pt_type == CLOCK_VIRTUAL);
   1233 			timespecadd(&ts, &ptn->pt_time.it_value, &ts);
   1234 		}
   1235 		LIST_FIRST(&pts->pts_virtual) = NULL;
   1236 		if (ptn) {
   1237 			KASSERT(ptn->pt_type == CLOCK_VIRTUAL);
   1238 			timespecadd(&ts, &ptn->pt_time.it_value,
   1239 			    &ptn->pt_time.it_value);
   1240 			LIST_INSERT_HEAD(&pts->pts_virtual, ptn, pt_list);
   1241 		}
   1242 		timespecclear(&ts);
   1243 		for (ptn = LIST_FIRST(&pts->pts_prof);
   1244 		     ptn && ptn != pts->pts_timers[ITIMER_PROF];
   1245 		     ptn = LIST_NEXT(ptn, pt_list)) {
   1246 			KASSERT(ptn->pt_type == CLOCK_PROF);
   1247 			timespecadd(&ts, &ptn->pt_time.it_value, &ts);
   1248 		}
   1249 		LIST_FIRST(&pts->pts_prof) = NULL;
   1250 		if (ptn) {
   1251 			KASSERT(ptn->pt_type == CLOCK_PROF);
   1252 			timespecadd(&ts, &ptn->pt_time.it_value,
   1253 			    &ptn->pt_time.it_value);
   1254 			LIST_INSERT_HEAD(&pts->pts_prof, ptn, pt_list);
   1255 		}
   1256 		i = 3;
   1257 	}
   1258 	for ( ; i < TIMER_MAX; i++) {
   1259 		if (pts->pts_timers[i] != NULL) {
   1260 			itimerfree(pts, i);
   1261 			mutex_spin_enter(&timer_lock);
   1262 		}
   1263 	}
   1264 	if (pts->pts_timers[0] == NULL && pts->pts_timers[1] == NULL &&
   1265 	    pts->pts_timers[2] == NULL) {
   1266 		p->p_timers = NULL;
   1267 		mutex_spin_exit(&timer_lock);
   1268 		pool_put(&ptimers_pool, pts);
   1269 	} else
   1270 		mutex_spin_exit(&timer_lock);
   1271 }
   1272 
   1273 static void
   1274 itimerfree(struct ptimers *pts, int index)
   1275 {
   1276 	struct ptimer *pt;
   1277 
   1278 	KASSERT(mutex_owned(&timer_lock));
   1279 
   1280 	pt = pts->pts_timers[index];
   1281 	pts->pts_timers[index] = NULL;
   1282 	if (!CLOCK_VIRTUAL_P(pt->pt_type))
   1283 		callout_halt(&pt->pt_ch, &timer_lock);
   1284 	if (pt->pt_queued)
   1285 		TAILQ_REMOVE(&timer_queue, pt, pt_chain);
   1286 	mutex_spin_exit(&timer_lock);
   1287 	if (!CLOCK_VIRTUAL_P(pt->pt_type))
   1288 		callout_destroy(&pt->pt_ch);
   1289 	pool_put(&ptimer_pool, pt);
   1290 }
   1291 
   1292 /*
   1293  * Decrement an interval timer by a specified number
   1294  * of nanoseconds, which must be less than a second,
   1295  * i.e. < 1000000000.  If the timer expires, then reload
   1296  * it.  In this case, carry over (nsec - old value) to
   1297  * reduce the value reloaded into the timer so that
   1298  * the timer does not drift.  This routine assumes
   1299  * that it is called in a context where the timers
   1300  * on which it is operating cannot change in value.
   1301  */
   1302 static int
   1303 itimerdecr(struct ptimer *pt, int nsec)
   1304 {
   1305 	struct itimerspec *itp;
   1306 
   1307 	KASSERT(mutex_owned(&timer_lock));
   1308 	KASSERT(CLOCK_VIRTUAL_P(pt->pt_type));
   1309 
   1310 	itp = &pt->pt_time;
   1311 	if (itp->it_value.tv_nsec < nsec) {
   1312 		if (itp->it_value.tv_sec == 0) {
   1313 			/* expired, and already in next interval */
   1314 			nsec -= itp->it_value.tv_nsec;
   1315 			goto expire;
   1316 		}
   1317 		itp->it_value.tv_nsec += 1000000000;
   1318 		itp->it_value.tv_sec--;
   1319 	}
   1320 	itp->it_value.tv_nsec -= nsec;
   1321 	nsec = 0;
   1322 	if (timespecisset(&itp->it_value))
   1323 		return (1);
   1324 	/* expired, exactly at end of interval */
   1325 expire:
   1326 	if (timespecisset(&itp->it_interval)) {
   1327 		itp->it_value = itp->it_interval;
   1328 		itp->it_value.tv_nsec -= nsec;
   1329 		if (itp->it_value.tv_nsec < 0) {
   1330 			itp->it_value.tv_nsec += 1000000000;
   1331 			itp->it_value.tv_sec--;
   1332 		}
   1333 		timer_settime(pt);
   1334 	} else
   1335 		itp->it_value.tv_nsec = 0;		/* sec is already 0 */
   1336 	return (0);
   1337 }
   1338 
   1339 static void
   1340 itimerfire(struct ptimer *pt)
   1341 {
   1342 
   1343 	KASSERT(mutex_owned(&timer_lock));
   1344 
   1345 	/*
   1346 	 * XXX Can overrun, but we don't do signal queueing yet, anyway.
   1347 	 * XXX Relying on the clock interrupt is stupid.
   1348 	 */
   1349 	if (pt->pt_ev.sigev_notify != SIGEV_SIGNAL || pt->pt_queued) {
   1350 		return;
   1351 	}
   1352 	TAILQ_INSERT_TAIL(&timer_queue, pt, pt_chain);
   1353 	pt->pt_queued = true;
   1354 	softint_schedule(timer_sih);
   1355 }
   1356 
   1357 void
   1358 timer_tick(lwp_t *l, bool user)
   1359 {
   1360 	struct ptimers *pts;
   1361 	struct ptimer *pt;
   1362 	proc_t *p;
   1363 
   1364 	p = l->l_proc;
   1365 	if (p->p_timers == NULL)
   1366 		return;
   1367 
   1368 	mutex_spin_enter(&timer_lock);
   1369 	if ((pts = l->l_proc->p_timers) != NULL) {
   1370 		/*
   1371 		 * Run current process's virtual and profile time, as needed.
   1372 		 */
   1373 		if (user && (pt = LIST_FIRST(&pts->pts_virtual)) != NULL)
   1374 			if (itimerdecr(pt, tick * 1000) == 0)
   1375 				itimerfire(pt);
   1376 		if ((pt = LIST_FIRST(&pts->pts_prof)) != NULL)
   1377 			if (itimerdecr(pt, tick * 1000) == 0)
   1378 				itimerfire(pt);
   1379 	}
   1380 	mutex_spin_exit(&timer_lock);
   1381 }
   1382 
   1383 static void
   1384 timer_intr(void *cookie)
   1385 {
   1386 	ksiginfo_t ksi;
   1387 	struct ptimer *pt;
   1388 	proc_t *p;
   1389 
   1390 	mutex_enter(proc_lock);
   1391 	mutex_spin_enter(&timer_lock);
   1392 	while ((pt = TAILQ_FIRST(&timer_queue)) != NULL) {
   1393 		TAILQ_REMOVE(&timer_queue, pt, pt_chain);
   1394 		KASSERT(pt->pt_queued);
   1395 		pt->pt_queued = false;
   1396 
   1397 		if (pt->pt_proc->p_timers == NULL) {
   1398 			/* Process is dying. */
   1399 			continue;
   1400 		}
   1401 		p = pt->pt_proc;
   1402 		if (pt->pt_ev.sigev_notify != SIGEV_SIGNAL) {
   1403 			continue;
   1404 		}
   1405 		if (sigismember(&p->p_sigpend.sp_set, pt->pt_ev.sigev_signo)) {
   1406 			pt->pt_overruns++;
   1407 			continue;
   1408 		}
   1409 
   1410 		KSI_INIT(&ksi);
   1411 		ksi.ksi_signo = pt->pt_ev.sigev_signo;
   1412 		ksi.ksi_code = SI_TIMER;
   1413 		ksi.ksi_value = pt->pt_ev.sigev_value;
   1414 		pt->pt_poverruns = pt->pt_overruns;
   1415 		pt->pt_overruns = 0;
   1416 		mutex_spin_exit(&timer_lock);
   1417 		kpsignal(p, &ksi, NULL);
   1418 		mutex_spin_enter(&timer_lock);
   1419 	}
   1420 	mutex_spin_exit(&timer_lock);
   1421 	mutex_exit(proc_lock);
   1422 }
   1423 
   1424 /*
   1425  * Check if the time will wrap if set to ts.
   1426  *
   1427  * ts - timespec describing the new time
   1428  * delta - the delta between the current time and ts
   1429  */
   1430 bool
   1431 time_wraps(struct timespec *ts, struct timespec *delta)
   1432 {
   1433 
   1434 	/*
   1435 	 * Don't allow the time to be set forward so far it
   1436 	 * will wrap and become negative, thus allowing an
   1437 	 * attacker to bypass the next check below.  The
   1438 	 * cutoff is 1 year before rollover occurs, so even
   1439 	 * if the attacker uses adjtime(2) to move the time
   1440 	 * past the cutoff, it will take a very long time
   1441 	 * to get to the wrap point.
   1442 	 */
   1443 	if ((ts->tv_sec > LLONG_MAX - 365*24*60*60) ||
   1444 	    (delta->tv_sec < 0 || delta->tv_nsec < 0))
   1445 		return true;
   1446 
   1447 	return false;
   1448 }
   1449