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