xref: /netbsd-src/sys/kern/kern_time.c (revision 2a399c6883d870daece976daec6ffa7bb7f934ce)
1 /*	$NetBSD: kern_time.c,v 1.30 1997/10/15 17:04:08 mycroft Exp $	*/
2 
3 /*
4  * Copyright (c) 1982, 1986, 1989, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  *
35  *	@(#)kern_time.c	8.1 (Berkeley) 6/10/93
36  */
37 
38 #include <sys/param.h>
39 #include <sys/resourcevar.h>
40 #include <sys/kernel.h>
41 #include <sys/systm.h>
42 #include <sys/proc.h>
43 #include <sys/vnode.h>
44 #include <sys/signalvar.h>
45 #include <sys/syslog.h>
46 
47 #include <sys/mount.h>
48 #include <sys/syscallargs.h>
49 
50 #if defined(NFS) || defined(NFSSERVER)
51 #include <nfs/rpcv2.h>
52 #include <nfs/nfsproto.h>
53 #include <nfs/nfs_var.h>
54 #endif
55 
56 #include <machine/cpu.h>
57 
58 static int	settime __P((struct timeval *));
59 
60 /*
61  * Time of day and interval timer support.
62  *
63  * These routines provide the kernel entry points to get and set
64  * the time-of-day and per-process interval timers.  Subroutines
65  * here provide support for adding and subtracting timeval structures
66  * and decrementing interval timers, optionally reloading the interval
67  * timers when they expire.
68  */
69 
70 /* This function is used by clock_settime and settimeofday */
71 static int
72 settime(tv)
73 	struct timeval *tv;
74 {
75 	struct timeval delta;
76 	int s;
77 
78 	/* WHAT DO WE DO ABOUT PENDING REAL-TIME TIMEOUTS??? */
79 	s = splclock();
80 	timersub(tv, &time, &delta);
81 	if ((delta.tv_sec < 0 || delta.tv_usec < 0) && securelevel > 1)
82 		return (EPERM);
83 #ifdef notyet
84 	if ((delta.tv_sec < 86400) && securelevel > 0)
85 		return (EPERM);
86 #endif
87 	time = *tv;
88 	(void) splsoftclock();
89 	timeradd(&boottime, &delta, &boottime);
90 	timeradd(&runtime, &delta, &runtime);
91 #	if defined(NFS) || defined(NFSSERVER)
92 		nqnfs_lease_updatetime(delta.tv_sec);
93 #	endif
94 	splx(s);
95 	resettodr();
96 	return (0);
97 }
98 
99 /* ARGSUSED */
100 int
101 sys_clock_gettime(p, v, retval)
102 	struct proc *p;
103 	void *v;
104 	register_t *retval;
105 {
106 	register struct sys_clock_gettime_args /* {
107 		syscallarg(clockid_t) clock_id;
108 		syscallarg(struct timespec *) tp;
109 	} */ *uap = v;
110 	clockid_t clock_id;
111 	struct timeval atv;
112 	struct timespec ats;
113 
114 	clock_id = SCARG(uap, clock_id);
115 	if (clock_id != CLOCK_REALTIME)
116 		return (EINVAL);
117 
118 	microtime(&atv);
119 	TIMEVAL_TO_TIMESPEC(&atv,&ats);
120 
121 	return copyout(&ats, SCARG(uap, tp), sizeof(ats));
122 }
123 
124 /* ARGSUSED */
125 int
126 sys_clock_settime(p, v, retval)
127 	struct proc *p;
128 	void *v;
129 	register_t *retval;
130 {
131 	register struct sys_clock_settime_args /* {
132 		syscallarg(clockid_t) clock_id;
133 		syscallarg(const struct timespec *) tp;
134 	} */ *uap = v;
135 	clockid_t clock_id;
136 	struct timeval atv;
137 	struct timespec ats;
138 	int error;
139 
140 	if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
141 		return (error);
142 
143 	clock_id = SCARG(uap, clock_id);
144 	if (clock_id != CLOCK_REALTIME)
145 		return (EINVAL);
146 
147 	if ((error = copyin(SCARG(uap, tp), &ats, sizeof(ats))) != 0)
148 		return (error);
149 
150 	TIMESPEC_TO_TIMEVAL(&atv,&ats);
151 	if ((error = settime(&atv)))
152 		return (error);
153 
154 	return 0;
155 }
156 
157 int
158 sys_clock_getres(p, v, retval)
159 	struct proc *p;
160 	void *v;
161 	register_t *retval;
162 {
163 	register struct sys_clock_getres_args /* {
164 		syscallarg(clockid_t) clock_id;
165 		syscallarg(struct timespec *) tp;
166 	} */ *uap = v;
167 	clockid_t clock_id;
168 	struct timespec ts;
169 	int error = 0;
170 
171 	clock_id = SCARG(uap, clock_id);
172 	if (clock_id != CLOCK_REALTIME)
173 		return (EINVAL);
174 
175 	if (SCARG(uap, tp)) {
176 		ts.tv_sec = 0;
177 		ts.tv_nsec = 1000000000 / hz;
178 
179 		error = copyout(&ts, SCARG(uap, tp), sizeof (ts));
180 	}
181 
182 	return error;
183 }
184 
185 /* ARGSUSED */
186 int
187 sys_nanosleep(p, v, retval)
188 	struct proc *p;
189 	void *v;
190 	register_t *retval;
191 {
192 	static int nanowait;
193 	register struct sys_nanosleep_args/* {
194 		syscallarg(struct timespec *) rqtp;
195 		syscallarg(struct timespec *) rmtp;
196 	} */ *uap = v;
197 	struct timespec rqt;
198 	struct timespec rmt;
199 	struct timeval atv, utv;
200 	int error, s, timo;
201 
202 	error = copyin((caddr_t)SCARG(uap, rqtp), (caddr_t)&rqt,
203 		       sizeof(struct timespec));
204 	if (error)
205 		return (error);
206 
207 	TIMESPEC_TO_TIMEVAL(&atv,&rqt)
208 	if (itimerfix(&atv))
209 		return (EINVAL);
210 
211 	s = splclock();
212 	timeradd(&atv,&time,&atv);
213 	timo = hzto(&atv);
214 	/*
215 	 * Avoid inadvertantly sleeping forever
216 	 */
217 	if (timo == 0)
218 		timo = 1;
219 	splx(s);
220 
221 	error = tsleep(&nanowait, PWAIT | PCATCH, "nanosleep", timo);
222 	if (error == ERESTART)
223 		error = EINTR;
224 	if (error == EWOULDBLOCK)
225 		error = 0;
226 
227 	if (SCARG(uap, rmtp)) {
228 		int error;
229 
230 		s = splclock();
231 		utv = time;
232 		splx(s);
233 
234 		timersub(&atv, &utv, &utv);
235 		if (utv.tv_sec < 0)
236 			timerclear(&utv);
237 
238 		TIMEVAL_TO_TIMESPEC(&utv,&rmt);
239 		error = copyout((caddr_t)&rmt, (caddr_t)SCARG(uap,rmtp),
240 			sizeof(rmt));
241 		if (error)
242 			return (error);
243 	}
244 
245 	return error;
246 }
247 
248 /* ARGSUSED */
249 int
250 sys_gettimeofday(p, v, retval)
251 	struct proc *p;
252 	void *v;
253 	register_t *retval;
254 {
255 	register struct sys_gettimeofday_args /* {
256 		syscallarg(struct timeval *) tp;
257 		syscallarg(struct timezone *) tzp;
258 	} */ *uap = v;
259 	struct timeval atv;
260 	int error = 0;
261 	struct timezone tzfake;
262 
263 	if (SCARG(uap, tp)) {
264 		microtime(&atv);
265 		error = copyout(&atv, SCARG(uap, tp), sizeof (atv));
266 		if (error)
267 			return (error);
268 	}
269 	if (SCARG(uap, tzp)) {
270 		/*
271 		 * NetBSD has no kernel notion of timezone, so we just
272 		 * fake up a timezone struct and return it if demanded.
273 		 */
274 		tzfake.tz_minuteswest = 0;
275 		tzfake.tz_dsttime = 0;
276 		error = copyout(&tzfake, SCARG(uap, tzp), sizeof (tzfake));
277 	}
278 	return (error);
279 }
280 
281 /* ARGSUSED */
282 int
283 sys_settimeofday(p, v, retval)
284 	struct proc *p;
285 	void *v;
286 	register_t *retval;
287 {
288 	struct sys_settimeofday_args /* {
289 		syscallarg(const struct timeval *) tv;
290 		syscallarg(const struct timezone *) tzp;
291 	} */ *uap = v;
292 	struct timeval atv;
293 	struct timezone atz;
294 	int error;
295 
296 	if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
297 		return (error);
298 	/* Verify all parameters before changing time. */
299 	if (SCARG(uap, tv) && (error = copyin(SCARG(uap, tv),
300 	    &atv, sizeof(atv))))
301 		return (error);
302 	/* XXX since we don't use tz, probably no point in doing copyin. */
303 	if (SCARG(uap, tzp) && (error = copyin(SCARG(uap, tzp),
304 	    &atz, sizeof(atz))))
305 		return (error);
306 	if (SCARG(uap, tv))
307 		if ((error = settime(&atv)))
308 			return (error);
309 	/*
310 	 * NetBSD has no kernel notion of timezone, and only an
311 	 * obsolete program would try to set it, so we log a warning.
312 	 */
313 	if (SCARG(uap, tzp))
314 		log(LOG_WARNING, "pid %d attempted to set the "
315 		    "(obsolete) kernel timezone.", p->p_pid);
316 	return (0);
317 }
318 
319 int	tickdelta;			/* current clock skew, us. per tick */
320 long	timedelta;			/* unapplied time correction, us. */
321 long	bigadj = 1000000;		/* use 10x skew above bigadj us. */
322 
323 /* ARGSUSED */
324 int
325 sys_adjtime(p, v, retval)
326 	struct proc *p;
327 	void *v;
328 	register_t *retval;
329 {
330 	register struct sys_adjtime_args /* {
331 		syscallarg(const struct timeval *) delta;
332 		syscallarg(struct timeval *) olddelta;
333 	} */ *uap = v;
334 	struct timeval atv;
335 	register long ndelta, ntickdelta, odelta;
336 	int s, error;
337 
338 	if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
339 		return (error);
340 
341 	error = copyin(SCARG(uap, delta), &atv, sizeof(struct timeval));
342 	if (error)
343 		return (error);
344 
345 	/*
346 	 * Compute the total correction and the rate at which to apply it.
347 	 * Round the adjustment down to a whole multiple of the per-tick
348 	 * delta, so that after some number of incremental changes in
349 	 * hardclock(), tickdelta will become zero, lest the correction
350 	 * overshoot and start taking us away from the desired final time.
351 	 */
352 	ndelta = atv.tv_sec * 1000000 + atv.tv_usec;
353 	if (ndelta > bigadj)
354 		ntickdelta = 10 * tickadj;
355 	else
356 		ntickdelta = tickadj;
357 	if (ndelta % ntickdelta)
358 		ndelta = ndelta / ntickdelta * ntickdelta;
359 
360 	/*
361 	 * To make hardclock()'s job easier, make the per-tick delta negative
362 	 * if we want time to run slower; then hardclock can simply compute
363 	 * tick + tickdelta, and subtract tickdelta from timedelta.
364 	 */
365 	if (ndelta < 0)
366 		ntickdelta = -ntickdelta;
367 	s = splclock();
368 	odelta = timedelta;
369 	timedelta = ndelta;
370 	tickdelta = ntickdelta;
371 	splx(s);
372 
373 	if (SCARG(uap, olddelta)) {
374 		atv.tv_sec = odelta / 1000000;
375 		atv.tv_usec = odelta % 1000000;
376 		(void) copyout(&atv, SCARG(uap, olddelta),
377 		    sizeof(struct timeval));
378 	}
379 	return (0);
380 }
381 
382 /*
383  * Get value of an interval timer.  The process virtual and
384  * profiling virtual time timers are kept in the p_stats area, since
385  * they can be swapped out.  These are kept internally in the
386  * way they are specified externally: in time until they expire.
387  *
388  * The real time interval timer is kept in the process table slot
389  * for the process, and its value (it_value) is kept as an
390  * absolute time rather than as a delta, so that it is easy to keep
391  * periodic real-time signals from drifting.
392  *
393  * Virtual time timers are processed in the hardclock() routine of
394  * kern_clock.c.  The real time timer is processed by a timeout
395  * routine, called from the softclock() routine.  Since a callout
396  * may be delayed in real time due to interrupt processing in the system,
397  * it is possible for the real time timeout routine (realitexpire, given below),
398  * to be delayed in real time past when it is supposed to occur.  It
399  * does not suffice, therefore, to reload the real timer .it_value from the
400  * real time timers .it_interval.  Rather, we compute the next time in
401  * absolute time the timer should go off.
402  */
403 /* ARGSUSED */
404 int
405 sys_getitimer(p, v, retval)
406 	struct proc *p;
407 	void *v;
408 	register_t *retval;
409 {
410 	register struct sys_getitimer_args /* {
411 		syscallarg(int) which;
412 		syscallarg(struct itimerval *) itv;
413 	} */ *uap = v;
414 	int which = SCARG(uap, which);
415 	struct itimerval aitv;
416 	int s;
417 
418 	if ((u_int)which > ITIMER_PROF)
419 		return (EINVAL);
420 	s = splclock();
421 	if (which == ITIMER_REAL) {
422 		/*
423 		 * Convert from absolute to relative time in .it_value
424 		 * part of real time timer.  If time for real time timer
425 		 * has passed return 0, else return difference between
426 		 * current time and time for the timer to go off.
427 		 */
428 		aitv = p->p_realtimer;
429 		if (timerisset(&aitv.it_value))
430 			if (timercmp(&aitv.it_value, &time, <))
431 				timerclear(&aitv.it_value);
432 			else
433 				timersub(&aitv.it_value, &time, &aitv.it_value);
434 	} else
435 		aitv = p->p_stats->p_timer[which];
436 	splx(s);
437 	return (copyout(&aitv, SCARG(uap, itv), sizeof (struct itimerval)));
438 }
439 
440 /* ARGSUSED */
441 int
442 sys_setitimer(p, v, retval)
443 	struct proc *p;
444 	register void *v;
445 	register_t *retval;
446 {
447 	register struct sys_setitimer_args /* {
448 		syscallarg(int) which;
449 		syscallarg(const struct itimerval *) itv;
450 		syscallarg(struct itimerval *) oitv;
451 	} */ *uap = v;
452 	int which = SCARG(uap, which);
453 	struct sys_getitimer_args getargs;
454 	struct itimerval aitv;
455 	register const struct itimerval *itvp;
456 	int s, error;
457 
458 	if ((u_int)which > ITIMER_PROF)
459 		return (EINVAL);
460 	itvp = SCARG(uap, itv);
461 	if (itvp && (error = copyin(itvp, &aitv, sizeof(struct itimerval))))
462 		return (error);
463 	if (SCARG(uap, oitv) != NULL) {
464 		SCARG(&getargs, which) = which;
465 		SCARG(&getargs, itv) = SCARG(uap, oitv);
466 		if ((error = sys_getitimer(p, &getargs, retval)) != 0)
467 			return (error);
468 	}
469 	if (itvp == 0)
470 		return (0);
471 	if (itimerfix(&aitv.it_value) || itimerfix(&aitv.it_interval))
472 		return (EINVAL);
473 	s = splclock();
474 	if (which == ITIMER_REAL) {
475 		untimeout(realitexpire, p);
476 		if (timerisset(&aitv.it_value)) {
477 			timeradd(&aitv.it_value, &time, &aitv.it_value);
478 			timeout(realitexpire, p, hzto(&aitv.it_value));
479 		}
480 		p->p_realtimer = aitv;
481 	} else
482 		p->p_stats->p_timer[which] = aitv;
483 	splx(s);
484 	return (0);
485 }
486 
487 /*
488  * Real interval timer expired:
489  * send process whose timer expired an alarm signal.
490  * If time is not set up to reload, then just return.
491  * Else compute next time timer should go off which is > current time.
492  * This is where delay in processing this timeout causes multiple
493  * SIGALRM calls to be compressed into one.
494  */
495 void
496 realitexpire(arg)
497 	void *arg;
498 {
499 	register struct proc *p;
500 	int s;
501 
502 	p = (struct proc *)arg;
503 	psignal(p, SIGALRM);
504 	if (!timerisset(&p->p_realtimer.it_interval)) {
505 		timerclear(&p->p_realtimer.it_value);
506 		return;
507 	}
508 	for (;;) {
509 		s = splclock();
510 		timeradd(&p->p_realtimer.it_value,
511 		    &p->p_realtimer.it_interval, &p->p_realtimer.it_value);
512 		if (timercmp(&p->p_realtimer.it_value, &time, >)) {
513 			timeout(realitexpire, p,
514 			    hzto(&p->p_realtimer.it_value));
515 			splx(s);
516 			return;
517 		}
518 		splx(s);
519 	}
520 }
521 
522 /*
523  * Check that a proposed value to load into the .it_value or
524  * .it_interval part of an interval timer is acceptable, and
525  * fix it to have at least minimal value (i.e. if it is less
526  * than the resolution of the clock, round it up.)
527  */
528 int
529 itimerfix(tv)
530 	struct timeval *tv;
531 {
532 
533 	if (tv->tv_sec < 0 || tv->tv_sec > 100000000 ||
534 	    tv->tv_usec < 0 || tv->tv_usec >= 1000000)
535 		return (EINVAL);
536 	if (tv->tv_sec == 0 && tv->tv_usec != 0 && tv->tv_usec < tick)
537 		tv->tv_usec = tick;
538 	return (0);
539 }
540 
541 /*
542  * Decrement an interval timer by a specified number
543  * of microseconds, which must be less than a second,
544  * i.e. < 1000000.  If the timer expires, then reload
545  * it.  In this case, carry over (usec - old value) to
546  * reduce the value reloaded into the timer so that
547  * the timer does not drift.  This routine assumes
548  * that it is called in a context where the timers
549  * on which it is operating cannot change in value.
550  */
551 int
552 itimerdecr(itp, usec)
553 	register struct itimerval *itp;
554 	int usec;
555 {
556 
557 	if (itp->it_value.tv_usec < usec) {
558 		if (itp->it_value.tv_sec == 0) {
559 			/* expired, and already in next interval */
560 			usec -= itp->it_value.tv_usec;
561 			goto expire;
562 		}
563 		itp->it_value.tv_usec += 1000000;
564 		itp->it_value.tv_sec--;
565 	}
566 	itp->it_value.tv_usec -= usec;
567 	usec = 0;
568 	if (timerisset(&itp->it_value))
569 		return (1);
570 	/* expired, exactly at end of interval */
571 expire:
572 	if (timerisset(&itp->it_interval)) {
573 		itp->it_value = itp->it_interval;
574 		itp->it_value.tv_usec -= usec;
575 		if (itp->it_value.tv_usec < 0) {
576 			itp->it_value.tv_usec += 1000000;
577 			itp->it_value.tv_sec--;
578 		}
579 	} else
580 		itp->it_value.tv_usec = 0;		/* sec is already 0 */
581 	return (0);
582 }
583