/*-
* Copyright (c) 2000, 2004, 2005, 2007, 2008, 2009, 2020
* The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Christopher G. Demetriou, by Andrew Doran, and by Jason R. Thorpe.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Copyright (c) 1982, 1986, 1989, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)kern_time.c 8.4 (Berkeley) 5/26/95
*/
/*
* Check if the time will wrap if set to ts.
*
* ts - timespec describing the new time
* delta - the delta between the current time and ts
*/
bool
time_wraps(struct timespec *ts, struct timespec *delta)
{
/*
* Don't allow the time to be set forward so far it
* will wrap and become negative, thus allowing an
* attacker to bypass the next check below. The
* cutoff is 1 year before rollover occurs, so even
* if the attacker uses adjtime(2) to move the time
* past the cutoff, it will take a very long time
* to get to the wrap point.
*/
if ((ts->tv_sec > LLONG_MAX - 365*24*60*60) ||
(delta->tv_sec < 0 || delta->tv_nsec < 0))
return true;
return false;
}
/*
* itimer_lock:
*
* Acquire the interval timer data lock.
*/
void
itimer_lock(void)
{
mutex_spin_enter(&itimer_mutex);
}
/*
* itimer_unlock:
*
* Release the interval timer data lock.
*/
void
itimer_unlock(void)
{
mutex_spin_exit(&itimer_mutex);
}
/*
* itimer_lock_held:
*
* Check that the interval timer lock is held for diagnostic
* assertions.
*/
inline bool __diagused
itimer_lock_held(void)
{
return mutex_owned(&itimer_mutex);
}
/*
* Time of day and interval timer support.
*
* These routines provide the kernel entry points to get and set
* the time-of-day and per-process interval timers. Subroutines
* here provide support for adding and subtracting timeval structures
* and decrementing interval timers, optionally reloading the interval
* timers when they expire.
*/
/* This function is used by clock_settime and settimeofday */
static int
settime1(struct proc *p, const struct timespec *ts, bool check_kauth)
{
struct timespec delta, now;
/*
* The time being set to an unreasonable value will cause
* unreasonable system behaviour.
*/
if (ts->tv_sec < 0 || ts->tv_sec > (1LL << 36))
return EINVAL;
/*
* Notify pending CLOCK_REALTIME timers about the real time change.
* There may be inactive timers on this list, but this happens
* comparatively less often than timers firing, and so it's better
* to put the extra checks here than to complicate the other code
* path.
*/
struct itimer *it;
itimer_lock();
LIST_FOREACH(it, &itimer_realtime_changed_notify, it_rtchgq) {
KASSERT(it->it_ops->ito_realtime_changed != NULL);
if (timespecisset(&it->it_time.it_value)) {
(*it->it_ops->ito_realtime_changed)(it);
}
}
itimer_unlock();
if (SCARG(uap, tp)) {
memset(&atv, 0, sizeof(atv));
microtime(&atv);
error = copyout(&atv, SCARG(uap, tp), sizeof(atv));
if (error)
return error;
}
if (SCARG(uap, tzp)) {
/*
* NetBSD has no kernel notion of time zone, so we just
* fake up a timezone struct and return it if demanded.
*/
tzfake.tz_minuteswest = 0;
tzfake.tz_dsttime = 0;
error = copyout(&tzfake, SCARG(uap, tzp), sizeof(tzfake));
}
return error;
}
/*
* NetBSD has no kernel notion of time zone, and only an
* obsolete program would try to set it, so we log a warning.
*/
if (utzp)
log(LOG_WARNING, "pid %d attempted to set the "
"(obsolete) kernel time zone\n", l->l_proc->p_pid);
if (utv == NULL)
return 0;
if (userspace) {
if ((error = copyin(utv, &atv, sizeof(atv))) != 0)
return error;
utv = &atv;
}
if (utv->tv_usec < 0 || utv->tv_usec >= 1000000)
return EINVAL;
if (delta) {
mutex_spin_enter(&timecounter_lock);
/*
* XXX This should maybe just report failure to
* userland for nonsense deltas.
*/
if (delta->tv_sec > INT64_MAX/1000000 - 1) {
time_adjtime = INT64_MAX;
} else if (delta->tv_sec < INT64_MIN/1000000 + 1) {
time_adjtime = INT64_MIN;
} else {
time_adjtime = delta->tv_sec * 1000000
+ MAX(-999999, MIN(999999, delta->tv_usec));
}
if (time_adjtime) {
/* We need to save the system time during shutdown */
time_adjusted |= 1;
}
mutex_spin_exit(&timecounter_lock);
}
}
/*
* Interval timer support.
*
* The itimer_*() routines provide generic support for interval timers,
* both real (CLOCK_REALTIME, CLOCK_MONOTIME), and virtual (CLOCK_VIRTUAL,
* CLOCK_PROF).
*
* Real timers keep their deadline as an absolute time, and are fired
* by a callout. Virtual timers are kept as a linked-list of deltas,
* and are processed by hardclock().
*
* Because the real time timer callout may be delayed in real time due
* to interrupt processing on the system, it is possible for the real
* time timeout routine (itimer_callout()) run past after its deadline.
* It does not suffice, therefore, to reload the real timer .it_value
* from the timer's .it_interval. Rather, we compute the next deadline
* in absolute time based on the current time and the .it_interval value,
* and report any overruns.
*
* Note that while the virtual timers are supported in a generic fashion
* here, they only (currently) make sense as per-process timers, and thus
* only really work for that case.
*/
/*
* itimer_init:
*
* Initialize the common data for an interval timer.
*/
void
itimer_init(struct itimer * const it, const struct itimer_ops * const ops,
clockid_t const id, struct itlist * const itl)
{
/*
* itimer_poison:
*
* Poison an interval timer, preventing it from being scheduled
* or processed, in preparation for freeing the timer.
*/
void
itimer_poison(struct itimer * const it)
{
KASSERT(itimer_lock_held());
it->it_dying = true;
/*
* For non-virtual timers, stop the callout, or wait for it to
* run if it has already fired. It cannot restart again after
* this point: the callout won't restart itself when dying, no
* other users holding the lock can restart it, and any other
* users waiting for callout_halt concurrently (itimer_settime)
* will restart from the top.
*/
if (!CLOCK_VIRTUAL_P(it->it_clockid)) {
callout_halt(&it->it_ch, &itimer_mutex);
if (it->it_clockid == CLOCK_REALTIME &&
it->it_ops->ito_realtime_changed != NULL) {
LIST_REMOVE(it, it_rtchgq);
}
}
}
/*
* itimer_fini:
*
* Release resources used by an interval timer.
*
* N.B. itimer_lock must be held on entry, and is released on exit.
*/
void
itimer_fini(struct itimer * const it)
{
KASSERT(itimer_lock_held());
/* All done with the global state. */
itimer_unlock();
/* Destroy the callout, if needed. */
if (!CLOCK_VIRTUAL_P(it->it_clockid))
callout_destroy(&it->it_ch);
}
/*
* itimer_decr:
*
* Decrement an interval timer by a specified number of nanoseconds,
* which must be less than a second, i.e. < 1000000000. If the timer
* expires, then reload it. In this case, carry over (nsec - old value)
* to reduce the value reloaded into the timer so that the timer does
* not drift. This routine assumes that it is called in a context where
* the timers on which it is operating cannot change in value.
*
* Returns true if the timer has expired.
*/
static bool
itimer_decr(struct itimer *it, int nsec)
{
struct itimerspec *itp;
int error __diagused;
/*
* Don't need to check tshzto() return value, here.
* callout_schedule() does it for us.
*/
callout_schedule(&it->it_ch,
(it->it_clockid == CLOCK_MONOTONIC
? tshztoup(&it->it_time.it_value)
: tshzto(&it->it_time.it_value)));
}
/*
* itimer_callout:
*
* Callout to expire a non-virtual timer. Queue it up for processing,
* and then reload, if it is configured to do so.
*
* N.B. A delay in processing this callout causes multiple
* SIGALRM calls to be compressed into one.
*/
static void
itimer_callout(void *arg)
{
struct timespec now, next;
struct itimer * const it = arg;
int overruns;
itimer_lock();
(*it->it_ops->ito_fire)(it);
if (!timespecisset(&it->it_time.it_interval)) {
timespecclear(&it->it_time.it_value);
itimer_unlock();
return;
}
/*
* Given the current itimer value and interval and the time
* now, compute the next itimer value and count overruns.
*/
itimer_transition(&it->it_time, &now, &next, &overruns);
it->it_time.it_value = next;
it->it_overruns += overruns;
/*
* Reset the callout, if it's not going away.
*/
if (!it->it_dying)
itimer_arm_real(it);
itimer_unlock();
}
/*
* itimer_settime:
*
* Set up the given interval timer. The value in it->it_time.it_value
* is taken to be an absolute time for CLOCK_REALTIME/CLOCK_MONOTONIC
* timers and a relative time for CLOCK_VIRTUAL/CLOCK_PROF timers.
*
* If the callout had already fired but not yet run, fails with
* ERESTART -- caller must restart from the top to look up a timer.
*
* Caller is responsible for validating it->it_value and
* it->it_interval, e.g. with itimerfix or itimespecfix.
*/
int
itimer_settime(struct itimer *it)
{
struct itimer *itn, *pitn;
struct itlist *itl;
if (!CLOCK_VIRTUAL_P(it->it_clockid)) {
/*
* Try to stop the callout. However, if it had already
* fired, we have to drop the lock to wait for it, so
* the world may have changed and pt may not be there
* any more. In that case, tell the caller to start
* over from the top.
*/
if (callout_halt(&it->it_ch, &itimer_mutex))
return ERESTART;
KASSERT(!it->it_dying);
/* Now we can touch it and start it up again. */
if (timespecisset(&it->it_time.it_value))
itimer_arm_real(it);
} else {
if (it->it_active) {
itn = LIST_NEXT(it, it_list);
LIST_REMOVE(it, it_list);
for ( ; itn; itn = LIST_NEXT(itn, it_list))
timespecadd(&it->it_time.it_value,
&itn->it_time.it_value,
&itn->it_time.it_value);
}
if (timespecisset(&it->it_time.it_value)) {
itl = it->it_vlist;
for (itn = LIST_FIRST(itl), pitn = NULL;
itn && timespeccmp(&it->it_time.it_value,
&itn->it_time.it_value, >);
pitn = itn, itn = LIST_NEXT(itn, it_list))
timespecsub(&it->it_time.it_value,
&itn->it_time.it_value,
&it->it_time.it_value);
if (pitn)
LIST_INSERT_AFTER(pitn, it, it_list);
else
LIST_INSERT_HEAD(itl, it, it_list);
*aits = it->it_time;
if (!CLOCK_VIRTUAL_P(it->it_clockid)) {
/*
* Convert from absolute to relative time in .it_value
* part of real time timer. If time for real time
* timer has passed return 0, else return difference
* between current time and time for the timer to go
* off.
*/
if (timespecisset(&aits->it_value)) {
if (it->it_clockid == CLOCK_REALTIME) {
getnanotime(&now);
} else { /* CLOCK_MONOTONIC */
getnanouptime(&now);
}
if (timespeccmp(&aits->it_value, &now, <))
timespecclear(&aits->it_value);
else
timespecsub(&aits->it_value, &now,
&aits->it_value);
}
} else if (it->it_active) {
for (itn = LIST_FIRST(it->it_vlist); itn && itn != it;
itn = LIST_NEXT(itn, it_list))
timespecadd(&aits->it_value,
&itn->it_time.it_value, &aits->it_value);
KASSERT(itn != NULL); /* it should be findable on the list */
} else
timespecclear(&aits->it_value);
}
/*
* Per-process timer support.
*
* Both the BSD getitimer() family and the POSIX timer_*() family of
* routines are supported.
*
* All timers are kept in an array pointed to by p_timers, which is
* allocated on demand - many processes don't use timers at all. The
* first four elements in this array are reserved for the BSD timers:
* element 0 is ITIMER_REAL, element 1 is ITIMER_VIRTUAL, element
* 2 is ITIMER_PROF, and element 3 is ITIMER_MONOTONIC. The rest may be
* allocated by the timer_create() syscall.
*
* These timers are a "sub-class" of interval timer.
*/
/*
* ptimer_free:
*
* Free the per-process timer at the specified index.
*/
static void
ptimer_free(struct ptimers *pts, int index)
{
struct itimer *it;
struct ptimer *pt;
/*
* Remove it from the queue to be signalled. Must be done
* after itimer is poisoned, because we may have had to wait
* for the callout to complete.
*/
if (pt->pt_queued) {
TAILQ_REMOVE(&ptimer_queue, pt, pt_chain);
pt->pt_queued = false;
}
/*
* ptimers_alloc:
*
* Allocate a ptimers for the specified process.
*/
static struct ptimers *
ptimers_alloc(struct proc *p)
{
struct ptimers *pts;
int i;
pts = kmem_alloc(sizeof(*pts), KM_SLEEP);
LIST_INIT(&pts->pts_virtual);
LIST_INIT(&pts->pts_prof);
for (i = 0; i < TIMER_MAX; i++)
pts->pts_timers[i] = NULL;
itimer_lock();
if (p->p_timers == NULL) {
p->p_timers = pts;
itimer_unlock();
return pts;
}
itimer_unlock();
kmem_free(pts, sizeof(*pts));
return p->p_timers;
}
/*
* ptimers_free:
*
* Clean up the per-process timers. If "which" is set to TIMERS_ALL,
* then clean up all timers and free all the data structures. If
* "which" is set to TIMERS_POSIX, only clean up the timers allocated
* by timer_create(), not the BSD setitimer() timers, and only free the
* structure if none of those remain.
*
* This function is exported because it is needed in the exec and
* exit code paths.
*/
void
ptimers_free(struct proc *p, int which)
{
struct ptimers *pts;
struct itimer *itn;
struct timespec ts;
int i;
if (p->p_timers == NULL)
return;
pts = p->p_timers;
itimer_lock();
if (which == TIMERS_ALL) {
p->p_timers = NULL;
i = 0;
} else {
timespecclear(&ts);
for (itn = LIST_FIRST(&pts->pts_virtual);
itn && itn != pts->pts_timers[ITIMER_VIRTUAL];
itn = LIST_NEXT(itn, it_list)) {
KASSERT(itn->it_clockid == CLOCK_VIRTUAL);
timespecadd(&ts, &itn->it_time.it_value, &ts);
}
LIST_FIRST(&pts->pts_virtual) = NULL;
if (itn) {
KASSERT(itn->it_clockid == CLOCK_VIRTUAL);
timespecadd(&ts, &itn->it_time.it_value,
&itn->it_time.it_value);
LIST_INSERT_HEAD(&pts->pts_virtual, itn, it_list);
}
timespecclear(&ts);
for (itn = LIST_FIRST(&pts->pts_prof);
itn && itn != pts->pts_timers[ITIMER_PROF];
itn = LIST_NEXT(itn, it_list)) {
KASSERT(itn->it_clockid == CLOCK_PROF);
timespecadd(&ts, &itn->it_time.it_value, &ts);
}
LIST_FIRST(&pts->pts_prof) = NULL;
if (itn) {
KASSERT(itn->it_clockid == CLOCK_PROF);
timespecadd(&ts, &itn->it_time.it_value,
&itn->it_time.it_value);
LIST_INSERT_HEAD(&pts->pts_prof, itn, it_list);
}
i = TIMER_MIN;
}
for ( ; i < TIMER_MAX; i++) {
if (pts->pts_timers[i] != NULL) {
/* Free the timer and release the lock. */
ptimer_free(pts, i);
/* Reacquire the lock for the next one. */
itimer_lock();
}
}
if (pts->pts_timers[0] == NULL && pts->pts_timers[1] == NULL &&
pts->pts_timers[2] == NULL && pts->pts_timers[3] == NULL) {
p->p_timers = NULL;
itimer_unlock();
kmem_free(pts, sizeof(*pts));
} else
itimer_unlock();
}
/*
* XXX Can overrun, but we don't do signal queueing yet, anyway.
* XXX Relying on the clock interrupt is stupid.
*/
if (pt->pt_ev.sigev_notify != SIGEV_SIGNAL) {
return;
}
if (ovalue)
itimer_gettime(it, ovalue);
it->it_time = val;
/*
* If we've been passed a relative time for a realtime timer,
* convert it to absolute; if an absolute time for a virtual
* timer, convert it to relative and make sure we don't set it
* to zero, which would cancel the timer, or let it go
* negative, which would confuse the comparison tests.
*/
if (timespecisset(&it->it_time.it_value)) {
if (!CLOCK_VIRTUAL_P(it->it_clockid)) {
if ((flags & TIMER_ABSTIME) == 0) {
if (it->it_clockid == CLOCK_REALTIME) {
getnanotime(&now);
} else { /* CLOCK_MONOTONIC */
getnanouptime(&now);
}
timespecadd(&it->it_time.it_value, &now,
&it->it_time.it_value);
}
} else {
if ((flags & TIMER_ABSTIME) != 0) {
getnanotime(&now);
timespecsub(&it->it_time.it_value, &now,
&it->it_time.it_value);
if (!timespecisset(&it->it_time.it_value) ||
it->it_time.it_value.tv_sec < 0) {
it->it_time.it_value.tv_sec = 0;
it->it_time.it_value.tv_nsec = 1;
}
}
}
}
/*
* sys_timer_getoverrun:
*
* System call to return the number of times a POSIX timer has
* expired while a notification was already pending. The counter
* is reset when a timer expires and a notification can be posted.
*/
int
sys_timer_getoverrun(struct lwp *l, const struct sys_timer_getoverrun_args *uap,
register_t *retval)
{
/* {
syscallarg(timer_t) timerid;
} */
struct proc *p = l->l_proc;
struct ptimers *pts;
int timerid;
struct itimer *it;
struct ptimer *pt;
/*
* ptimer_tick:
*
* Called from hardclock() to decrement per-process virtual timers.
*/
void
ptimer_tick(lwp_t *l, bool user)
{
struct ptimers *pts;
struct itimer *it;
proc_t *p;
p = l->l_proc;
if (p->p_timers == NULL)
return;
itimer_lock();
if ((pts = l->l_proc->p_timers) != NULL) {
/*
* Run current process's virtual and profile time, as needed.
*/
if (user && (it = LIST_FIRST(&pts->pts_virtual)) != NULL)
if (itimer_decr(it, tick * 1000))
(*it->it_ops->ito_fire)(it);
if ((it = LIST_FIRST(&pts->pts_prof)) != NULL)
if (itimer_decr(it, tick * 1000))
(*it->it_ops->ito_fire)(it);
}
itimer_unlock();
}
p = pt->pt_proc;
if (p->p_timers == NULL) {
/* Process is dying. */
continue;
}
if (pt->pt_ev.sigev_notify != SIGEV_SIGNAL) {
continue;
}
if (sigismember(&p->p_sigpend.sp_set, pt->pt_ev.sigev_signo)) {
it->it_overruns++;
continue;
}