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