partially fix pctcpu and userland rescheduling. We really have to distribute
[dragonfly.git] / sys / kern / kern_time.c
1 /*
2  * Copyright (c) 1982, 1986, 1989, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *      @(#)kern_time.c 8.1 (Berkeley) 6/10/93
34  * $FreeBSD: src/sys/kern/kern_time.c,v 1.68.2.1 2002/10/01 08:00:41 bde Exp $
35  * $DragonFly: src/sys/kern/kern_time.c,v 1.4 2003/06/25 03:55:57 dillon Exp $
36  */
37
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/buf.h>
41 #include <sys/sysproto.h>
42 #include <sys/resourcevar.h>
43 #include <sys/signalvar.h>
44 #include <sys/kernel.h>
45 #include <sys/systm.h>
46 #include <sys/sysent.h>
47 #include <sys/proc.h>
48 #include <sys/time.h>
49 #include <sys/vnode.h>
50 #include <vm/vm.h>
51 #include <vm/vm_extern.h>
52
53 struct timezone tz;
54
55 /*
56  * Time of day and interval timer support.
57  *
58  * These routines provide the kernel entry points to get and set
59  * the time-of-day and per-process interval timers.  Subroutines
60  * here provide support for adding and subtracting timeval structures
61  * and decrementing interval timers, optionally reloading the interval
62  * timers when they expire.
63  */
64
65 static int      nanosleep1 __P((struct timespec *rqt,
66                     struct timespec *rmt));
67 static int      settime __P((struct timeval *));
68 static void     timevalfix __P((struct timeval *));
69 static void     no_lease_updatetime __P((int));
70
71 static void 
72 no_lease_updatetime(deltat)
73         int deltat;
74 {
75 }
76
77 void (*lease_updatetime) __P((int))  = no_lease_updatetime;
78
79 static int
80 settime(tv)
81         struct timeval *tv;
82 {
83         struct timeval delta, tv1, tv2;
84         static struct timeval maxtime, laststep;
85         struct timespec ts;
86         int s;
87
88         s = splclock();
89         microtime(&tv1);
90         delta = *tv;
91         timevalsub(&delta, &tv1);
92
93         /*
94          * If the system is secure, we do not allow the time to be 
95          * set to a value earlier than 1 second less than the highest
96          * time we have yet seen. The worst a miscreant can do in
97          * this circumstance is "freeze" time. He couldn't go
98          * back to the past.
99          *
100          * We similarly do not allow the clock to be stepped more
101          * than one second, nor more than once per second. This allows
102          * a miscreant to make the clock march double-time, but no worse.
103          */
104         if (securelevel > 1) {
105                 if (delta.tv_sec < 0 || delta.tv_usec < 0) {
106                         /*
107                          * Update maxtime to latest time we've seen.
108                          */
109                         if (tv1.tv_sec > maxtime.tv_sec)
110                                 maxtime = tv1;
111                         tv2 = *tv;
112                         timevalsub(&tv2, &maxtime);
113                         if (tv2.tv_sec < -1) {
114                                 tv->tv_sec = maxtime.tv_sec - 1;
115                                 printf("Time adjustment clamped to -1 second\n");
116                         }
117                 } else {
118                         if (tv1.tv_sec == laststep.tv_sec) {
119                                 splx(s);
120                                 return (EPERM);
121                         }
122                         if (delta.tv_sec > 1) {
123                                 tv->tv_sec = tv1.tv_sec + 1;
124                                 printf("Time adjustment clamped to +1 second\n");
125                         }
126                         laststep = *tv;
127                 }
128         }
129
130         ts.tv_sec = tv->tv_sec;
131         ts.tv_nsec = tv->tv_usec * 1000;
132         set_timecounter(&ts);
133         (void) splsoftclock();
134         lease_updatetime(delta.tv_sec);
135         splx(s);
136         resettodr();
137         return (0);
138 }
139
140 #ifndef _SYS_SYSPROTO_H_
141 struct clock_gettime_args {
142         clockid_t clock_id;
143         struct  timespec *tp;
144 };
145 #endif
146
147 /* ARGSUSED */
148 int
149 clock_gettime(struct clock_gettime_args *uap)
150 {
151         struct timespec ats;
152
153         if (SCARG(uap, clock_id) != CLOCK_REALTIME)
154                 return (EINVAL);
155         nanotime(&ats);
156         return (copyout(&ats, SCARG(uap, tp), sizeof(ats)));
157 }
158
159 #ifndef _SYS_SYSPROTO_H_
160 struct clock_settime_args {
161         clockid_t clock_id;
162         const struct    timespec *tp;
163 };
164 #endif
165
166 /* ARGSUSED */
167 int
168 clock_settime(struct clock_settime_args *uap)
169 {
170         struct thread *td = curthread;
171         struct timeval atv;
172         struct timespec ats;
173         int error;
174
175         if ((error = suser(td)) != 0)
176                 return (error);
177         if (SCARG(uap, clock_id) != CLOCK_REALTIME)
178                 return (EINVAL);
179         if ((error = copyin(SCARG(uap, tp), &ats, sizeof(ats))) != 0)
180                 return (error);
181         if (ats.tv_nsec < 0 || ats.tv_nsec >= 1000000000)
182                 return (EINVAL);
183         /* XXX Don't convert nsec->usec and back */
184         TIMESPEC_TO_TIMEVAL(&atv, &ats);
185         if ((error = settime(&atv)))
186                 return (error);
187         return (0);
188 }
189
190 #ifndef _SYS_SYSPROTO_H_
191 struct clock_getres_args {
192         clockid_t clock_id;
193         struct  timespec *tp;
194 };
195 #endif
196
197 int
198 clock_getres(struct clock_getres_args *uap)
199 {
200         struct timespec ts;
201         int error;
202
203         if (SCARG(uap, clock_id) != CLOCK_REALTIME)
204                 return (EINVAL);
205         error = 0;
206         if (SCARG(uap, tp)) {
207                 ts.tv_sec = 0;
208                 /*
209                  * Round up the result of the division cheaply by adding 1.
210                  * Rounding up is especially important if rounding down
211                  * would give 0.  Perfect rounding is unimportant.
212                  */
213                 ts.tv_nsec = 1000000000 / timecounter->tc_frequency + 1;
214                 error = copyout(&ts, SCARG(uap, tp), sizeof(ts));
215         }
216         return (error);
217 }
218
219 static int nanowait;
220
221 static int
222 nanosleep1(struct timespec *rqt, struct timespec *rmt)
223 {
224         struct timespec ts, ts2, ts3;
225         struct timeval tv;
226         int error;
227
228         if (rqt->tv_nsec < 0 || rqt->tv_nsec >= 1000000000)
229                 return (EINVAL);
230         if (rqt->tv_sec < 0 || (rqt->tv_sec == 0 && rqt->tv_nsec == 0))
231                 return (0);
232         getnanouptime(&ts);
233         timespecadd(&ts, rqt);
234         TIMESPEC_TO_TIMEVAL(&tv, rqt);
235         for (;;) {
236                 error = tsleep(&nanowait, PWAIT | PCATCH, "nanslp",
237                     tvtohz(&tv));
238                 getnanouptime(&ts2);
239                 if (error != EWOULDBLOCK) {
240                         if (error == ERESTART)
241                                 error = EINTR;
242                         if (rmt != NULL) {
243                                 timespecsub(&ts, &ts2);
244                                 if (ts.tv_sec < 0)
245                                         timespecclear(&ts);
246                                 *rmt = ts;
247                         }
248                         return (error);
249                 }
250                 if (timespeccmp(&ts2, &ts, >=))
251                         return (0);
252                 ts3 = ts;
253                 timespecsub(&ts3, &ts2);
254                 TIMESPEC_TO_TIMEVAL(&tv, &ts3);
255         }
256 }
257
258 #ifndef _SYS_SYSPROTO_H_
259 struct nanosleep_args {
260         struct  timespec *rqtp;
261         struct  timespec *rmtp;
262 };
263 #endif
264
265 /* ARGSUSED */
266 int
267 nanosleep(struct nanosleep_args *uap)
268 {
269         struct timespec rmt, rqt;
270         int error, error2;
271
272         error = copyin(SCARG(uap, rqtp), &rqt, sizeof(rqt));
273         if (error)
274                 return (error);
275         if (SCARG(uap, rmtp))
276                 if (!useracc((caddr_t)SCARG(uap, rmtp), sizeof(rmt), 
277                     VM_PROT_WRITE))
278                         return (EFAULT);
279         error = nanosleep1(&rqt, &rmt);
280         if (error && SCARG(uap, rmtp)) {
281                 error2 = copyout(&rmt, SCARG(uap, rmtp), sizeof(rmt));
282                 if (error2)     /* XXX shouldn't happen, did useracc() above */
283                         return (error2);
284         }
285         return (error);
286 }
287
288 #ifndef _SYS_SYSPROTO_H_
289 struct gettimeofday_args {
290         struct  timeval *tp;
291         struct  timezone *tzp;
292 };
293 #endif
294 /* ARGSUSED */
295 int
296 gettimeofday(struct gettimeofday_args *uap)
297 {
298         struct timeval atv;
299         int error = 0;
300
301         if (uap->tp) {
302                 microtime(&atv);
303                 if ((error = copyout((caddr_t)&atv, (caddr_t)uap->tp,
304                     sizeof (atv))))
305                         return (error);
306         }
307         if (uap->tzp)
308                 error = copyout((caddr_t)&tz, (caddr_t)uap->tzp,
309                     sizeof (tz));
310         return (error);
311 }
312
313 #ifndef _SYS_SYSPROTO_H_
314 struct settimeofday_args {
315         struct  timeval *tv;
316         struct  timezone *tzp;
317 };
318 #endif
319 /* ARGSUSED */
320 int
321 settimeofday(struct settimeofday_args *uap)
322 {
323         struct thread *td = curthread;
324         struct timeval atv;
325         struct timezone atz;
326         int error;
327
328         if ((error = suser(td)))
329                 return (error);
330         /* Verify all parameters before changing time. */
331         if (uap->tv) {
332                 if ((error = copyin((caddr_t)uap->tv, (caddr_t)&atv,
333                     sizeof(atv))))
334                         return (error);
335                 if (atv.tv_usec < 0 || atv.tv_usec >= 1000000)
336                         return (EINVAL);
337         }
338         if (uap->tzp &&
339             (error = copyin((caddr_t)uap->tzp, (caddr_t)&atz, sizeof(atz))))
340                 return (error);
341         if (uap->tv && (error = settime(&atv)))
342                 return (error);
343         if (uap->tzp)
344                 tz = atz;
345         return (0);
346 }
347
348 int     tickdelta;                      /* current clock skew, us. per tick */
349 long    timedelta;                      /* unapplied time correction, us. */
350 static long     bigadj = 1000000;       /* use 10x skew above bigadj us. */
351
352 #ifndef _SYS_SYSPROTO_H_
353 struct adjtime_args {
354         struct timeval *delta;
355         struct timeval *olddelta;
356 };
357 #endif
358 /* ARGSUSED */
359 int
360 adjtime(struct adjtime_args *uap)
361 {
362         struct thread *td = curthread;
363         struct timeval atv;
364         long ndelta, ntickdelta, odelta;
365         int s, error;
366
367         if ((error = suser(td)))
368                 return (error);
369         if ((error =
370             copyin((caddr_t)uap->delta, (caddr_t)&atv, sizeof(struct timeval))))
371                 return (error);
372
373         /*
374          * Compute the total correction and the rate at which to apply it.
375          * Round the adjustment down to a whole multiple of the per-tick
376          * delta, so that after some number of incremental changes in
377          * hardclock(), tickdelta will become zero, lest the correction
378          * overshoot and start taking us away from the desired final time.
379          */
380         ndelta = atv.tv_sec * 1000000 + atv.tv_usec;
381         if (ndelta > bigadj || ndelta < -bigadj)
382                 ntickdelta = 10 * tickadj;
383         else
384                 ntickdelta = tickadj;
385         if (ndelta % ntickdelta)
386                 ndelta = ndelta / ntickdelta * ntickdelta;
387
388         /*
389          * To make hardclock()'s job easier, make the per-tick delta negative
390          * if we want time to run slower; then hardclock can simply compute
391          * tick + tickdelta, and subtract tickdelta from timedelta.
392          */
393         if (ndelta < 0)
394                 ntickdelta = -ntickdelta;
395         s = splclock();
396         odelta = timedelta;
397         timedelta = ndelta;
398         tickdelta = ntickdelta;
399         splx(s);
400
401         if (uap->olddelta) {
402                 atv.tv_sec = odelta / 1000000;
403                 atv.tv_usec = odelta % 1000000;
404                 (void) copyout((caddr_t)&atv, (caddr_t)uap->olddelta,
405                     sizeof(struct timeval));
406         }
407         return (0);
408 }
409
410 /*
411  * Get value of an interval timer.  The process virtual and
412  * profiling virtual time timers are kept in the p_stats area, since
413  * they can be swapped out.  These are kept internally in the
414  * way they are specified externally: in time until they expire.
415  *
416  * The real time interval timer is kept in the process table slot
417  * for the process, and its value (it_value) is kept as an
418  * absolute time rather than as a delta, so that it is easy to keep
419  * periodic real-time signals from drifting.
420  *
421  * Virtual time timers are processed in the hardclock() routine of
422  * kern_clock.c.  The real time timer is processed by a timeout
423  * routine, called from the softclock() routine.  Since a callout
424  * may be delayed in real time due to interrupt processing in the system,
425  * it is possible for the real time timeout routine (realitexpire, given below),
426  * to be delayed in real time past when it is supposed to occur.  It
427  * does not suffice, therefore, to reload the real timer .it_value from the
428  * real time timers .it_interval.  Rather, we compute the next time in
429  * absolute time the timer should go off.
430  */
431 #ifndef _SYS_SYSPROTO_H_
432 struct getitimer_args {
433         u_int   which;
434         struct  itimerval *itv;
435 };
436 #endif
437 /* ARGSUSED */
438 int
439 getitimer(struct getitimer_args *uap)
440 {
441         struct proc *p = curproc;
442         struct timeval ctv;
443         struct itimerval aitv;
444         int s;
445
446         if (uap->which > ITIMER_PROF)
447                 return (EINVAL);
448         s = splclock(); /* XXX still needed ? */
449         if (uap->which == ITIMER_REAL) {
450                 /*
451                  * Convert from absolute to relative time in .it_value
452                  * part of real time timer.  If time for real time timer
453                  * has passed return 0, else return difference between
454                  * current time and time for the timer to go off.
455                  */
456                 aitv = p->p_realtimer;
457                 if (timevalisset(&aitv.it_value)) {
458                         getmicrouptime(&ctv);
459                         if (timevalcmp(&aitv.it_value, &ctv, <))
460                                 timevalclear(&aitv.it_value);
461                         else
462                                 timevalsub(&aitv.it_value, &ctv);
463                 }
464         } else
465                 aitv = p->p_stats->p_timer[uap->which];
466         splx(s);
467         return (copyout((caddr_t)&aitv, (caddr_t)uap->itv,
468             sizeof (struct itimerval)));
469 }
470
471 #ifndef _SYS_SYSPROTO_H_
472 struct setitimer_args {
473         u_int   which;
474         struct  itimerval *itv, *oitv;
475 };
476 #endif
477 /* ARGSUSED */
478 int
479 setitimer(struct setitimer_args *uap)
480 {
481         struct itimerval aitv;
482         struct timeval ctv;
483         struct itimerval *itvp;
484         struct proc *p = curproc;
485         int s, error;
486
487         if (uap->which > ITIMER_PROF)
488                 return (EINVAL);
489         itvp = uap->itv;
490         if (itvp && (error = copyin((caddr_t)itvp, (caddr_t)&aitv,
491             sizeof(struct itimerval))))
492                 return (error);
493         if ((uap->itv = uap->oitv) &&
494             (error = getitimer((struct getitimer_args *)uap)))
495                 return (error);
496         if (itvp == 0)
497                 return (0);
498         if (itimerfix(&aitv.it_value))
499                 return (EINVAL);
500         if (!timevalisset(&aitv.it_value))
501                 timevalclear(&aitv.it_interval);
502         else if (itimerfix(&aitv.it_interval))
503                 return (EINVAL);
504         s = splclock(); /* XXX: still needed ? */
505         if (uap->which == ITIMER_REAL) {
506                 if (timevalisset(&p->p_realtimer.it_value))
507                         untimeout(realitexpire, (caddr_t)p, p->p_ithandle);
508                 if (timevalisset(&aitv.it_value)) 
509                         p->p_ithandle = timeout(realitexpire, (caddr_t)p,
510                                                 tvtohz(&aitv.it_value));
511                 getmicrouptime(&ctv);
512                 timevaladd(&aitv.it_value, &ctv);
513                 p->p_realtimer = aitv;
514         } else
515                 p->p_stats->p_timer[uap->which] = aitv;
516         splx(s);
517         return (0);
518 }
519
520 /*
521  * Real interval timer expired:
522  * send process whose timer expired an alarm signal.
523  * If time is not set up to reload, then just return.
524  * Else compute next time timer should go off which is > current time.
525  * This is where delay in processing this timeout causes multiple
526  * SIGALRM calls to be compressed into one.
527  * tvtohz() always adds 1 to allow for the time until the next clock
528  * interrupt being strictly less than 1 clock tick, but we don't want
529  * that here since we want to appear to be in sync with the clock
530  * interrupt even when we're delayed.
531  */
532 void
533 realitexpire(arg)
534         void *arg;
535 {
536         register struct proc *p;
537         struct timeval ctv, ntv;
538         int s;
539
540         p = (struct proc *)arg;
541         psignal(p, SIGALRM);
542         if (!timevalisset(&p->p_realtimer.it_interval)) {
543                 timevalclear(&p->p_realtimer.it_value);
544                 return;
545         }
546         for (;;) {
547                 s = splclock(); /* XXX: still neeeded ? */
548                 timevaladd(&p->p_realtimer.it_value,
549                     &p->p_realtimer.it_interval);
550                 getmicrouptime(&ctv);
551                 if (timevalcmp(&p->p_realtimer.it_value, &ctv, >)) {
552                         ntv = p->p_realtimer.it_value;
553                         timevalsub(&ntv, &ctv);
554                         p->p_ithandle = timeout(realitexpire, (caddr_t)p,
555                             tvtohz(&ntv) - 1);
556                         splx(s);
557                         return;
558                 }
559                 splx(s);
560         }
561 }
562
563 /*
564  * Check that a proposed value to load into the .it_value or
565  * .it_interval part of an interval timer is acceptable, and
566  * fix it to have at least minimal value (i.e. if it is less
567  * than the resolution of the clock, round it up.)
568  */
569 int
570 itimerfix(tv)
571         struct timeval *tv;
572 {
573
574         if (tv->tv_sec < 0 || tv->tv_sec > 100000000 ||
575             tv->tv_usec < 0 || tv->tv_usec >= 1000000)
576                 return (EINVAL);
577         if (tv->tv_sec == 0 && tv->tv_usec != 0 && tv->tv_usec < tick)
578                 tv->tv_usec = tick;
579         return (0);
580 }
581
582 /*
583  * Decrement an interval timer by a specified number
584  * of microseconds, which must be less than a second,
585  * i.e. < 1000000.  If the timer expires, then reload
586  * it.  In this case, carry over (usec - old value) to
587  * reduce the value reloaded into the timer so that
588  * the timer does not drift.  This routine assumes
589  * that it is called in a context where the timers
590  * on which it is operating cannot change in value.
591  */
592 int
593 itimerdecr(itp, usec)
594         register struct itimerval *itp;
595         int usec;
596 {
597
598         if (itp->it_value.tv_usec < usec) {
599                 if (itp->it_value.tv_sec == 0) {
600                         /* expired, and already in next interval */
601                         usec -= itp->it_value.tv_usec;
602                         goto expire;
603                 }
604                 itp->it_value.tv_usec += 1000000;
605                 itp->it_value.tv_sec--;
606         }
607         itp->it_value.tv_usec -= usec;
608         usec = 0;
609         if (timevalisset(&itp->it_value))
610                 return (1);
611         /* expired, exactly at end of interval */
612 expire:
613         if (timevalisset(&itp->it_interval)) {
614                 itp->it_value = itp->it_interval;
615                 itp->it_value.tv_usec -= usec;
616                 if (itp->it_value.tv_usec < 0) {
617                         itp->it_value.tv_usec += 1000000;
618                         itp->it_value.tv_sec--;
619                 }
620         } else
621                 itp->it_value.tv_usec = 0;              /* sec is already 0 */
622         return (0);
623 }
624
625 /*
626  * Add and subtract routines for timevals.
627  * N.B.: subtract routine doesn't deal with
628  * results which are before the beginning,
629  * it just gets very confused in this case.
630  * Caveat emptor.
631  */
632 void
633 timevaladd(t1, t2)
634         struct timeval *t1, *t2;
635 {
636
637         t1->tv_sec += t2->tv_sec;
638         t1->tv_usec += t2->tv_usec;
639         timevalfix(t1);
640 }
641
642 void
643 timevalsub(t1, t2)
644         struct timeval *t1, *t2;
645 {
646
647         t1->tv_sec -= t2->tv_sec;
648         t1->tv_usec -= t2->tv_usec;
649         timevalfix(t1);
650 }
651
652 static void
653 timevalfix(t1)
654         struct timeval *t1;
655 {
656
657         if (t1->tv_usec < 0) {
658                 t1->tv_sec--;
659                 t1->tv_usec += 1000000;
660         }
661         if (t1->tv_usec >= 1000000) {
662                 t1->tv_sec++;
663                 t1->tv_usec -= 1000000;
664         }
665 }