Merge branch 'vendor/LESS'
[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.40 2008/04/02 14:16:16 sephe 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/sysunion.h>
48 #include <sys/proc.h>
49 #include <sys/priv.h>
50 #include <sys/time.h>
51 #include <sys/vnode.h>
52 #include <sys/sysctl.h>
53 #include <sys/kern_syscall.h>
54 #include <vm/vm.h>
55 #include <vm/vm_extern.h>
56
57 #include <sys/msgport2.h>
58 #include <sys/thread2.h>
59 #include <sys/mplock2.h>
60
61 struct timezone tz;
62
63 /*
64  * Time of day and interval timer support.
65  *
66  * These routines provide the kernel entry points to get and set
67  * the time-of-day and per-process interval timers.  Subroutines
68  * here provide support for adding and subtracting timeval structures
69  * and decrementing interval timers, optionally reloading the interval
70  * timers when they expire.
71  */
72
73 int     nanosleep1(struct timespec *rqt, struct timespec *rmt);
74 static int      settime(struct timeval *);
75 static void     timevalfix(struct timeval *);
76
77 static int     sleep_hard_us = 100;
78 SYSCTL_INT(_kern, OID_AUTO, sleep_hard_us, CTLFLAG_RW, &sleep_hard_us, 0, "")
79
80 static int
81 settime(struct timeval *tv)
82 {
83         struct timeval delta, tv1, tv2;
84         static struct timeval maxtime, laststep;
85         struct timespec ts;
86         int origcpu;
87
88         if ((origcpu = mycpu->gd_cpuid) != 0)
89                 lwkt_setcpu_self(globaldata_find(0));
90
91         crit_enter();
92         microtime(&tv1);
93         delta = *tv;
94         timevalsub(&delta, &tv1);
95
96         /*
97          * If the system is secure, we do not allow the time to be 
98          * set to a value earlier than 1 second less than the highest
99          * time we have yet seen. The worst a miscreant can do in
100          * this circumstance is "freeze" time. He couldn't go
101          * back to the past.
102          *
103          * We similarly do not allow the clock to be stepped more
104          * than one second, nor more than once per second. This allows
105          * a miscreant to make the clock march double-time, but no worse.
106          */
107         if (securelevel > 1) {
108                 if (delta.tv_sec < 0 || delta.tv_usec < 0) {
109                         /*
110                          * Update maxtime to latest time we've seen.
111                          */
112                         if (tv1.tv_sec > maxtime.tv_sec)
113                                 maxtime = tv1;
114                         tv2 = *tv;
115                         timevalsub(&tv2, &maxtime);
116                         if (tv2.tv_sec < -1) {
117                                 tv->tv_sec = maxtime.tv_sec - 1;
118                                 kprintf("Time adjustment clamped to -1 second\n");
119                         }
120                 } else {
121                         if (tv1.tv_sec == laststep.tv_sec) {
122                                 crit_exit();
123                                 return (EPERM);
124                         }
125                         if (delta.tv_sec > 1) {
126                                 tv->tv_sec = tv1.tv_sec + 1;
127                                 kprintf("Time adjustment clamped to +1 second\n");
128                         }
129                         laststep = *tv;
130                 }
131         }
132
133         ts.tv_sec = tv->tv_sec;
134         ts.tv_nsec = tv->tv_usec * 1000;
135         set_timeofday(&ts);
136         crit_exit();
137
138         if (origcpu != 0)
139                 lwkt_setcpu_self(globaldata_find(origcpu));
140
141         resettodr();
142         return (0);
143 }
144
145 /*
146  * MPSAFE
147  */
148 int
149 kern_clock_gettime(clockid_t clock_id, struct timespec *ats)
150 {
151         int error = 0;
152
153         switch(clock_id) {
154         case CLOCK_REALTIME:
155                 nanotime(ats);
156                 break;
157         case CLOCK_MONOTONIC:
158                 nanouptime(ats);
159                 break;
160         default:
161                 error = EINVAL;
162                 break;
163         }
164         return (error);
165 }
166
167 /*
168  * MPSAFE
169  */
170 int
171 sys_clock_gettime(struct clock_gettime_args *uap)
172 {
173         struct timespec ats;
174         int error;
175
176         error = kern_clock_gettime(uap->clock_id, &ats);
177         if (error == 0)
178                 error = copyout(&ats, uap->tp, sizeof(ats));
179
180         return (error);
181 }
182
183 int
184 kern_clock_settime(clockid_t clock_id, struct timespec *ats)
185 {
186         struct thread *td = curthread;
187         struct timeval atv;
188         int error;
189
190         if ((error = priv_check(td, PRIV_CLOCK_SETTIME)) != 0)
191                 return (error);
192         if (clock_id != CLOCK_REALTIME)
193                 return (EINVAL);
194         if (ats->tv_nsec < 0 || ats->tv_nsec >= 1000000000)
195                 return (EINVAL);
196
197         TIMESPEC_TO_TIMEVAL(&atv, ats);
198         error = settime(&atv);
199         return (error);
200 }
201
202 /*
203  * MPALMOSTSAFE
204  */
205 int
206 sys_clock_settime(struct clock_settime_args *uap)
207 {
208         struct timespec ats;
209         int error;
210
211         if ((error = copyin(uap->tp, &ats, sizeof(ats))) != 0)
212                 return (error);
213
214         get_mplock();
215         error = kern_clock_settime(uap->clock_id, &ats);
216         rel_mplock();
217         return (error);
218 }
219
220 /*
221  * MPSAFE
222  */
223 int
224 kern_clock_getres(clockid_t clock_id, struct timespec *ts)
225 {
226         int error;
227
228         switch(clock_id) {
229         case CLOCK_REALTIME:
230         case CLOCK_MONOTONIC:
231                 /*
232                  * Round up the result of the division cheaply
233                  * by adding 1.  Rounding up is especially important
234                  * if rounding down would give 0.  Perfect rounding
235                  * is unimportant.
236                  */
237                 ts->tv_sec = 0;
238                 ts->tv_nsec = 1000000000 / sys_cputimer->freq + 1;
239                 error = 0;
240                 break;
241         default:
242                 error = EINVAL;
243                 break;
244         }
245
246         return(error);
247 }
248
249 /*
250  * MPSAFE
251  */
252 int
253 sys_clock_getres(struct clock_getres_args *uap)
254 {
255         int error;
256         struct timespec ts;
257
258         error = kern_clock_getres(uap->clock_id, &ts);
259         if (error == 0)
260                 error = copyout(&ts, uap->tp, sizeof(ts));
261
262         return (error);
263 }
264
265 /*
266  * nanosleep1()
267  *
268  *      This is a general helper function for nanosleep() (aka sleep() aka
269  *      usleep()).
270  *
271  *      If there is less then one tick's worth of time left and
272  *      we haven't done a yield, or the remaining microseconds is
273  *      ridiculously low, do a yield.  This avoids having
274  *      to deal with systimer overheads when the system is under
275  *      heavy loads.  If we have done a yield already then use
276  *      a systimer and an uninterruptable thread wait.
277  *
278  *      If there is more then a tick's worth of time left,
279  *      calculate the baseline ticks and use an interruptable
280  *      tsleep, then handle the fine-grained delay on the next
281  *      loop.  This usually results in two sleeps occuring, a long one
282  *      and a short one.
283  *
284  * MPSAFE
285  */
286 static void
287 ns1_systimer(systimer_t info, int in_ipi __unused,
288     struct intrframe *frame __unused)
289 {
290         lwkt_schedule(info->data);
291 }
292
293 int
294 nanosleep1(struct timespec *rqt, struct timespec *rmt)
295 {
296         static int nanowait;
297         struct timespec ts, ts2, ts3;
298         struct timeval tv;
299         int error;
300
301         if (rqt->tv_nsec < 0 || rqt->tv_nsec >= 1000000000)
302                 return (EINVAL);
303         /* XXX: imho this should return EINVAL at least for tv_sec < 0 */
304         if (rqt->tv_sec < 0 || (rqt->tv_sec == 0 && rqt->tv_nsec == 0))
305                 return (0);
306         nanouptime(&ts);
307         timespecadd(&ts, rqt);          /* ts = target timestamp compare */
308         TIMESPEC_TO_TIMEVAL(&tv, rqt);  /* tv = sleep interval */
309
310         for (;;) {
311                 int ticks;
312                 struct systimer info;
313
314                 ticks = tv.tv_usec / ustick;    /* approximate */
315
316                 if (tv.tv_sec == 0 && ticks == 0) {
317                         thread_t td = curthread;
318                         if (tv.tv_usec < sleep_hard_us) {
319                                 lwkt_user_yield();
320                         } else {
321                                 crit_enter_quick(td);
322                                 systimer_init_oneshot(&info, ns1_systimer,
323                                                 td, tv.tv_usec);
324                                 lwkt_deschedule_self(td);
325                                 crit_exit_quick(td);
326                                 lwkt_switch();
327                                 systimer_del(&info); /* make sure it's gone */
328                         }
329                         error = iscaught(td->td_lwp);
330                 } else if (tv.tv_sec == 0) {
331                         error = tsleep(&nanowait, PCATCH, "nanslp", ticks);
332                 } else {
333                         ticks = tvtohz_low(&tv); /* also handles overflow */
334                         error = tsleep(&nanowait, PCATCH, "nanslp", ticks);
335                 }
336                 nanouptime(&ts2);
337                 if (error && error != EWOULDBLOCK) {
338                         if (error == ERESTART)
339                                 error = EINTR;
340                         if (rmt != NULL) {
341                                 timespecsub(&ts, &ts2);
342                                 if (ts.tv_sec < 0)
343                                         timespecclear(&ts);
344                                 *rmt = ts;
345                         }
346                         return (error);
347                 }
348                 if (timespeccmp(&ts2, &ts, >=))
349                         return (0);
350                 ts3 = ts;
351                 timespecsub(&ts3, &ts2);
352                 TIMESPEC_TO_TIMEVAL(&tv, &ts3);
353         }
354 }
355
356 /*
357  * MPSAFE
358  */
359 int
360 sys_nanosleep(struct nanosleep_args *uap)
361 {
362         int error;
363         struct timespec rqt;
364         struct timespec rmt;
365
366         error = copyin(uap->rqtp, &rqt, sizeof(rqt));
367         if (error)
368                 return (error);
369
370         error = nanosleep1(&rqt, &rmt);
371
372         /*
373          * copyout the residual if nanosleep was interrupted.
374          */
375         if (error && uap->rmtp) {
376                 int error2;
377
378                 error2 = copyout(&rmt, uap->rmtp, sizeof(rmt));
379                 if (error2)
380                         error = error2;
381         }
382         return (error);
383 }
384
385 /*
386  * MPSAFE
387  */
388 int
389 sys_gettimeofday(struct gettimeofday_args *uap)
390 {
391         struct timeval atv;
392         int error = 0;
393
394         if (uap->tp) {
395                 microtime(&atv);
396                 if ((error = copyout((caddr_t)&atv, (caddr_t)uap->tp,
397                     sizeof (atv))))
398                         return (error);
399         }
400         if (uap->tzp)
401                 error = copyout((caddr_t)&tz, (caddr_t)uap->tzp,
402                     sizeof (tz));
403         return (error);
404 }
405
406 /*
407  * MPALMOSTSAFE
408  */
409 int
410 sys_settimeofday(struct settimeofday_args *uap)
411 {
412         struct thread *td = curthread;
413         struct timeval atv;
414         struct timezone atz;
415         int error;
416
417         if ((error = priv_check(td, PRIV_SETTIMEOFDAY)))
418                 return (error);
419         /* Verify all parameters before changing time. */
420         if (uap->tv) {
421                 if ((error = copyin((caddr_t)uap->tv, (caddr_t)&atv,
422                     sizeof(atv))))
423                         return (error);
424                 if (atv.tv_usec < 0 || atv.tv_usec >= 1000000)
425                         return (EINVAL);
426         }
427         if (uap->tzp &&
428             (error = copyin((caddr_t)uap->tzp, (caddr_t)&atz, sizeof(atz))))
429                 return (error);
430
431         get_mplock();
432         if (uap->tv && (error = settime(&atv))) {
433                 rel_mplock();
434                 return (error);
435         }
436         rel_mplock();
437         if (uap->tzp)
438                 tz = atz;
439         return (0);
440 }
441
442 static void
443 kern_adjtime_common(void)
444 {
445         if ((ntp_delta >= 0 && ntp_delta < ntp_default_tick_delta) ||
446             (ntp_delta < 0 && ntp_delta > -ntp_default_tick_delta))
447                 ntp_tick_delta = ntp_delta;
448         else if (ntp_delta > ntp_big_delta)
449                 ntp_tick_delta = 10 * ntp_default_tick_delta;
450         else if (ntp_delta < -ntp_big_delta)
451                 ntp_tick_delta = -10 * ntp_default_tick_delta;
452         else if (ntp_delta > 0)
453                 ntp_tick_delta = ntp_default_tick_delta;
454         else
455                 ntp_tick_delta = -ntp_default_tick_delta;
456 }
457
458 void
459 kern_adjtime(int64_t delta, int64_t *odelta)
460 {
461         int origcpu;
462
463         if ((origcpu = mycpu->gd_cpuid) != 0)
464                 lwkt_setcpu_self(globaldata_find(0));
465
466         crit_enter();
467         *odelta = ntp_delta;
468         ntp_delta = delta;
469         kern_adjtime_common();
470         crit_exit();
471
472         if (origcpu != 0)
473                 lwkt_setcpu_self(globaldata_find(origcpu));
474 }
475
476 static void
477 kern_get_ntp_delta(int64_t *delta)
478 {
479         int origcpu;
480
481         if ((origcpu = mycpu->gd_cpuid) != 0)
482                 lwkt_setcpu_self(globaldata_find(0));
483
484         crit_enter();
485         *delta = ntp_delta;
486         crit_exit();
487
488         if (origcpu != 0)
489                 lwkt_setcpu_self(globaldata_find(origcpu));
490 }
491
492 void
493 kern_reladjtime(int64_t delta)
494 {
495         int origcpu;
496
497         if ((origcpu = mycpu->gd_cpuid) != 0)
498                 lwkt_setcpu_self(globaldata_find(0));
499
500         crit_enter();
501         ntp_delta += delta;
502         kern_adjtime_common();
503         crit_exit();
504
505         if (origcpu != 0)
506                 lwkt_setcpu_self(globaldata_find(origcpu));
507 }
508
509 static void
510 kern_adjfreq(int64_t rate)
511 {
512         int origcpu;
513
514         if ((origcpu = mycpu->gd_cpuid) != 0)
515                 lwkt_setcpu_self(globaldata_find(0));
516
517         crit_enter();
518         ntp_tick_permanent = rate;
519         crit_exit();
520
521         if (origcpu != 0)
522                 lwkt_setcpu_self(globaldata_find(origcpu));
523 }
524
525 /*
526  * MPALMOSTSAFE
527  */
528 int
529 sys_adjtime(struct adjtime_args *uap)
530 {
531         struct thread *td = curthread;
532         struct timeval atv;
533         int64_t ndelta, odelta;
534         int error;
535
536         if ((error = priv_check(td, PRIV_ADJTIME)))
537                 return (error);
538         error = copyin(uap->delta, &atv, sizeof(struct timeval));
539         if (error)
540                 return (error);
541
542         /*
543          * Compute the total correction and the rate at which to apply it.
544          * Round the adjustment down to a whole multiple of the per-tick
545          * delta, so that after some number of incremental changes in
546          * hardclock(), tickdelta will become zero, lest the correction
547          * overshoot and start taking us away from the desired final time.
548          */
549         ndelta = (int64_t)atv.tv_sec * 1000000000 + atv.tv_usec * 1000;
550         get_mplock();
551         kern_adjtime(ndelta, &odelta);
552         rel_mplock();
553
554         if (uap->olddelta) {
555                 atv.tv_sec = odelta / 1000000000;
556                 atv.tv_usec = odelta % 1000000000 / 1000;
557                 copyout(&atv, uap->olddelta, sizeof(struct timeval));
558         }
559         return (0);
560 }
561
562 static int
563 sysctl_adjtime(SYSCTL_HANDLER_ARGS)
564 {
565         int64_t delta;
566         int error;
567
568         if (req->newptr != NULL) {
569                 if (priv_check(curthread, PRIV_ROOT))
570                         return (EPERM);
571                 error = SYSCTL_IN(req, &delta, sizeof(delta));
572                 if (error)
573                         return (error);
574                 kern_reladjtime(delta);
575         }
576
577         if (req->oldptr)
578                 kern_get_ntp_delta(&delta);
579         error = SYSCTL_OUT(req, &delta, sizeof(delta));
580         return (error);
581 }
582
583 /*
584  * delta is in nanoseconds.
585  */
586 static int
587 sysctl_delta(SYSCTL_HANDLER_ARGS)
588 {
589         int64_t delta, old_delta;
590         int error;
591
592         if (req->newptr != NULL) {
593                 if (priv_check(curthread, PRIV_ROOT))
594                         return (EPERM);
595                 error = SYSCTL_IN(req, &delta, sizeof(delta));
596                 if (error)
597                         return (error);
598                 kern_adjtime(delta, &old_delta);
599         }
600
601         if (req->oldptr != NULL)
602                 kern_get_ntp_delta(&old_delta);
603         error = SYSCTL_OUT(req, &old_delta, sizeof(old_delta));
604         return (error);
605 }
606
607 /*
608  * frequency is in nanoseconds per second shifted left 32.
609  * kern_adjfreq() needs it in nanoseconds per tick shifted left 32.
610  */
611 static int
612 sysctl_adjfreq(SYSCTL_HANDLER_ARGS)
613 {
614         int64_t freqdelta;
615         int error;
616
617         if (req->newptr != NULL) {
618                 if (priv_check(curthread, PRIV_ROOT))
619                         return (EPERM);
620                 error = SYSCTL_IN(req, &freqdelta, sizeof(freqdelta));
621                 if (error)
622                         return (error);
623                 
624                 freqdelta /= hz;
625                 kern_adjfreq(freqdelta);
626         }
627
628         if (req->oldptr != NULL)
629                 freqdelta = ntp_tick_permanent * hz;
630         error = SYSCTL_OUT(req, &freqdelta, sizeof(freqdelta));
631         if (error)
632                 return (error);
633
634         return (0);
635 }
636
637 SYSCTL_NODE(_kern, OID_AUTO, ntp, CTLFLAG_RW, 0, "NTP related controls");
638 SYSCTL_PROC(_kern_ntp, OID_AUTO, permanent,
639     CTLTYPE_QUAD|CTLFLAG_RW, 0, 0,
640     sysctl_adjfreq, "Q", "permanent correction per second");
641 SYSCTL_PROC(_kern_ntp, OID_AUTO, delta,
642     CTLTYPE_QUAD|CTLFLAG_RW, 0, 0,
643     sysctl_delta, "Q", "one-time delta");
644 SYSCTL_OPAQUE(_kern_ntp, OID_AUTO, big_delta, CTLFLAG_RD,
645     &ntp_big_delta, sizeof(ntp_big_delta), "Q",
646     "threshold for fast adjustment");
647 SYSCTL_OPAQUE(_kern_ntp, OID_AUTO, tick_delta, CTLFLAG_RD,
648     &ntp_tick_delta, sizeof(ntp_tick_delta), "LU",
649     "per-tick adjustment");
650 SYSCTL_OPAQUE(_kern_ntp, OID_AUTO, default_tick_delta, CTLFLAG_RD,
651     &ntp_default_tick_delta, sizeof(ntp_default_tick_delta), "LU",
652     "default per-tick adjustment");
653 SYSCTL_OPAQUE(_kern_ntp, OID_AUTO, next_leap_second, CTLFLAG_RW,
654     &ntp_leap_second, sizeof(ntp_leap_second), "LU",
655     "next leap second");
656 SYSCTL_INT(_kern_ntp, OID_AUTO, insert_leap_second, CTLFLAG_RW,
657     &ntp_leap_insert, 0, "insert or remove leap second");
658 SYSCTL_PROC(_kern_ntp, OID_AUTO, adjust,
659     CTLTYPE_QUAD|CTLFLAG_RW, 0, 0,
660     sysctl_adjtime, "Q", "relative adjust for delta");
661
662 /*
663  * Get value of an interval timer.  The process virtual and
664  * profiling virtual time timers are kept in the p_stats area, since
665  * they can be swapped out.  These are kept internally in the
666  * way they are specified externally: in time until they expire.
667  *
668  * The real time interval timer is kept in the process table slot
669  * for the process, and its value (it_value) is kept as an
670  * absolute time rather than as a delta, so that it is easy to keep
671  * periodic real-time signals from drifting.
672  *
673  * Virtual time timers are processed in the hardclock() routine of
674  * kern_clock.c.  The real time timer is processed by a timeout
675  * routine, called from the softclock() routine.  Since a callout
676  * may be delayed in real time due to interrupt processing in the system,
677  * it is possible for the real time timeout routine (realitexpire, given below),
678  * to be delayed in real time past when it is supposed to occur.  It
679  * does not suffice, therefore, to reload the real timer .it_value from the
680  * real time timers .it_interval.  Rather, we compute the next time in
681  * absolute time the timer should go off.
682  *
683  * MPALMOSTSAFE
684  */
685 int
686 sys_getitimer(struct getitimer_args *uap)
687 {
688         struct proc *p = curproc;
689         struct timeval ctv;
690         struct itimerval aitv;
691
692         if (uap->which > ITIMER_PROF)
693                 return (EINVAL);
694         get_mplock();
695         crit_enter();
696         if (uap->which == ITIMER_REAL) {
697                 /*
698                  * Convert from absolute to relative time in .it_value
699                  * part of real time timer.  If time for real time timer
700                  * has passed return 0, else return difference between
701                  * current time and time for the timer to go off.
702                  */
703                 aitv = p->p_realtimer;
704                 if (timevalisset(&aitv.it_value)) {
705                         getmicrouptime(&ctv);
706                         if (timevalcmp(&aitv.it_value, &ctv, <))
707                                 timevalclear(&aitv.it_value);
708                         else
709                                 timevalsub(&aitv.it_value, &ctv);
710                 }
711         } else {
712                 aitv = p->p_timer[uap->which];
713         }
714         crit_exit();
715         rel_mplock();
716         return (copyout(&aitv, uap->itv, sizeof (struct itimerval)));
717 }
718
719 /*
720  * MPALMOSTSAFE
721  */
722 int
723 sys_setitimer(struct setitimer_args *uap)
724 {
725         struct itimerval aitv;
726         struct timeval ctv;
727         struct itimerval *itvp;
728         struct proc *p = curproc;
729         int error;
730
731         if (uap->which > ITIMER_PROF)
732                 return (EINVAL);
733         itvp = uap->itv;
734         if (itvp && (error = copyin((caddr_t)itvp, (caddr_t)&aitv,
735             sizeof(struct itimerval))))
736                 return (error);
737         if ((uap->itv = uap->oitv) &&
738             (error = sys_getitimer((struct getitimer_args *)uap)))
739                 return (error);
740         if (itvp == 0)
741                 return (0);
742         if (itimerfix(&aitv.it_value))
743                 return (EINVAL);
744         if (!timevalisset(&aitv.it_value))
745                 timevalclear(&aitv.it_interval);
746         else if (itimerfix(&aitv.it_interval))
747                 return (EINVAL);
748         get_mplock();
749         crit_enter();
750         if (uap->which == ITIMER_REAL) {
751                 if (timevalisset(&p->p_realtimer.it_value))
752                         callout_stop(&p->p_ithandle);
753                 if (timevalisset(&aitv.it_value)) 
754                         callout_reset(&p->p_ithandle,
755                             tvtohz_high(&aitv.it_value), realitexpire, p);
756                 getmicrouptime(&ctv);
757                 timevaladd(&aitv.it_value, &ctv);
758                 p->p_realtimer = aitv;
759         } else {
760                 p->p_timer[uap->which] = aitv;
761         }
762         crit_exit();
763         rel_mplock();
764         return (0);
765 }
766
767 /*
768  * Real interval timer expired:
769  * send process whose timer expired an alarm signal.
770  * If time is not set up to reload, then just return.
771  * Else compute next time timer should go off which is > current time.
772  * This is where delay in processing this timeout causes multiple
773  * SIGALRM calls to be compressed into one.
774  * tvtohz_high() always adds 1 to allow for the time until the next clock
775  * interrupt being strictly less than 1 clock tick, but we don't want
776  * that here since we want to appear to be in sync with the clock
777  * interrupt even when we're delayed.
778  */
779 void
780 realitexpire(void *arg)
781 {
782         struct proc *p;
783         struct timeval ctv, ntv;
784
785         p = (struct proc *)arg;
786         ksignal(p, SIGALRM);
787         if (!timevalisset(&p->p_realtimer.it_interval)) {
788                 timevalclear(&p->p_realtimer.it_value);
789                 return;
790         }
791         for (;;) {
792                 crit_enter();
793                 timevaladd(&p->p_realtimer.it_value,
794                     &p->p_realtimer.it_interval);
795                 getmicrouptime(&ctv);
796                 if (timevalcmp(&p->p_realtimer.it_value, &ctv, >)) {
797                         ntv = p->p_realtimer.it_value;
798                         timevalsub(&ntv, &ctv);
799                         callout_reset(&p->p_ithandle, tvtohz_low(&ntv),
800                                       realitexpire, p);
801                         crit_exit();
802                         return;
803                 }
804                 crit_exit();
805         }
806 }
807
808 /*
809  * Check that a proposed value to load into the .it_value or
810  * .it_interval part of an interval timer is acceptable, and
811  * fix it to have at least minimal value (i.e. if it is less
812  * than the resolution of the clock, round it up.)
813  *
814  * MPSAFE
815  */
816 int
817 itimerfix(struct timeval *tv)
818 {
819
820         if (tv->tv_sec < 0 || tv->tv_sec > 100000000 ||
821             tv->tv_usec < 0 || tv->tv_usec >= 1000000)
822                 return (EINVAL);
823         if (tv->tv_sec == 0 && tv->tv_usec != 0 && tv->tv_usec < ustick)
824                 tv->tv_usec = ustick;
825         return (0);
826 }
827
828 /*
829  * Decrement an interval timer by a specified number
830  * of microseconds, which must be less than a second,
831  * i.e. < 1000000.  If the timer expires, then reload
832  * it.  In this case, carry over (usec - old value) to
833  * reduce the value reloaded into the timer so that
834  * the timer does not drift.  This routine assumes
835  * that it is called in a context where the timers
836  * on which it is operating cannot change in value.
837  */
838 int
839 itimerdecr(struct itimerval *itp, int usec)
840 {
841
842         if (itp->it_value.tv_usec < usec) {
843                 if (itp->it_value.tv_sec == 0) {
844                         /* expired, and already in next interval */
845                         usec -= itp->it_value.tv_usec;
846                         goto expire;
847                 }
848                 itp->it_value.tv_usec += 1000000;
849                 itp->it_value.tv_sec--;
850         }
851         itp->it_value.tv_usec -= usec;
852         usec = 0;
853         if (timevalisset(&itp->it_value))
854                 return (1);
855         /* expired, exactly at end of interval */
856 expire:
857         if (timevalisset(&itp->it_interval)) {
858                 itp->it_value = itp->it_interval;
859                 itp->it_value.tv_usec -= usec;
860                 if (itp->it_value.tv_usec < 0) {
861                         itp->it_value.tv_usec += 1000000;
862                         itp->it_value.tv_sec--;
863                 }
864         } else
865                 itp->it_value.tv_usec = 0;              /* sec is already 0 */
866         return (0);
867 }
868
869 /*
870  * Add and subtract routines for timevals.
871  * N.B.: subtract routine doesn't deal with
872  * results which are before the beginning,
873  * it just gets very confused in this case.
874  * Caveat emptor.
875  */
876 void
877 timevaladd(struct timeval *t1, const struct timeval *t2)
878 {
879
880         t1->tv_sec += t2->tv_sec;
881         t1->tv_usec += t2->tv_usec;
882         timevalfix(t1);
883 }
884
885 void
886 timevalsub(struct timeval *t1, const struct timeval *t2)
887 {
888
889         t1->tv_sec -= t2->tv_sec;
890         t1->tv_usec -= t2->tv_usec;
891         timevalfix(t1);
892 }
893
894 static void
895 timevalfix(struct timeval *t1)
896 {
897
898         if (t1->tv_usec < 0) {
899                 t1->tv_sec--;
900                 t1->tv_usec += 1000000;
901         }
902         if (t1->tv_usec >= 1000000) {
903                 t1->tv_sec++;
904                 t1->tv_usec -= 1000000;
905         }
906 }
907
908 /*
909  * ratecheck(): simple time-based rate-limit checking.
910  */
911 int
912 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
913 {
914         struct timeval tv, delta;
915         int rv = 0;
916
917         getmicrouptime(&tv);            /* NB: 10ms precision */
918         delta = tv;
919         timevalsub(&delta, lasttime);
920
921         /*
922          * check for 0,0 is so that the message will be seen at least once,
923          * even if interval is huge.
924          */
925         if (timevalcmp(&delta, mininterval, >=) ||
926             (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
927                 *lasttime = tv;
928                 rv = 1;
929         }
930
931         return (rv);
932 }
933
934 /*
935  * ppsratecheck(): packets (or events) per second limitation.
936  *
937  * Return 0 if the limit is to be enforced (e.g. the caller
938  * should drop a packet because of the rate limitation).
939  *
940  * maxpps of 0 always causes zero to be returned.  maxpps of -1
941  * always causes 1 to be returned; this effectively defeats rate
942  * limiting.
943  *
944  * Note that we maintain the struct timeval for compatibility
945  * with other bsd systems.  We reuse the storage and just monitor
946  * clock ticks for minimal overhead.  
947  */
948 int
949 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
950 {
951         int now;
952
953         /*
954          * Reset the last time and counter if this is the first call
955          * or more than a second has passed since the last update of
956          * lasttime.
957          */
958         now = ticks;
959         if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
960                 lasttime->tv_sec = now;
961                 *curpps = 1;
962                 return (maxpps != 0);
963         } else {
964                 (*curpps)++;            /* NB: ignore potential overflow */
965                 return (maxpps < 0 || *curpps < maxpps);
966         }
967 }
968