]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_time.c
Bump up the low range of cpuset numbers to account for the kernel cpuset.
[FreeBSD/FreeBSD.git] / sys / kern / kern_time.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
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. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *      @(#)kern_time.c 8.1 (Berkeley) 6/10/93
32  */
33
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36
37 #include "opt_ktrace.h"
38
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/limits.h>
42 #include <sys/clock.h>
43 #include <sys/lock.h>
44 #include <sys/mutex.h>
45 #include <sys/sysproto.h>
46 #include <sys/resourcevar.h>
47 #include <sys/signalvar.h>
48 #include <sys/kernel.h>
49 #include <sys/sleepqueue.h>
50 #include <sys/syscallsubr.h>
51 #include <sys/sysctl.h>
52 #include <sys/sysent.h>
53 #include <sys/priv.h>
54 #include <sys/proc.h>
55 #include <sys/posix4.h>
56 #include <sys/time.h>
57 #include <sys/timers.h>
58 #include <sys/timetc.h>
59 #include <sys/vnode.h>
60 #ifdef KTRACE
61 #include <sys/ktrace.h>
62 #endif
63
64 #include <vm/vm.h>
65 #include <vm/vm_extern.h>
66
67 #define MAX_CLOCKS      (CLOCK_MONOTONIC+1)
68 #define CPUCLOCK_BIT            0x80000000
69 #define CPUCLOCK_PROCESS_BIT    0x40000000
70 #define CPUCLOCK_ID_MASK        (~(CPUCLOCK_BIT|CPUCLOCK_PROCESS_BIT))
71 #define MAKE_THREAD_CPUCLOCK(tid)       (CPUCLOCK_BIT|(tid))
72 #define MAKE_PROCESS_CPUCLOCK(pid)      \
73         (CPUCLOCK_BIT|CPUCLOCK_PROCESS_BIT|(pid))
74
75 static struct kclock    posix_clocks[MAX_CLOCKS];
76 static uma_zone_t       itimer_zone = NULL;
77
78 /*
79  * Time of day and interval timer support.
80  *
81  * These routines provide the kernel entry points to get and set
82  * the time-of-day and per-process interval timers.  Subroutines
83  * here provide support for adding and subtracting timeval structures
84  * and decrementing interval timers, optionally reloading the interval
85  * timers when they expire.
86  */
87
88 static int      settime(struct thread *, struct timeval *);
89 static void     timevalfix(struct timeval *);
90 static int      user_clock_nanosleep(struct thread *td, clockid_t clock_id,
91                     int flags, const struct timespec *ua_rqtp,
92                     struct timespec *ua_rmtp);
93
94 static void     itimer_start(void);
95 static int      itimer_init(void *, int, int);
96 static void     itimer_fini(void *, int);
97 static void     itimer_enter(struct itimer *);
98 static void     itimer_leave(struct itimer *);
99 static struct itimer *itimer_find(struct proc *, int);
100 static void     itimers_alloc(struct proc *);
101 static int      realtimer_create(struct itimer *);
102 static int      realtimer_gettime(struct itimer *, struct itimerspec *);
103 static int      realtimer_settime(struct itimer *, int,
104                         struct itimerspec *, struct itimerspec *);
105 static int      realtimer_delete(struct itimer *);
106 static void     realtimer_clocktime(clockid_t, struct timespec *);
107 static void     realtimer_expire(void *);
108
109 static int      register_posix_clock(int, const struct kclock *);
110 void            itimer_fire(struct itimer *it);
111 int             itimespecfix(struct timespec *ts);
112
113 #define CLOCK_CALL(clock, call, arglist)                \
114         ((*posix_clocks[clock].call) arglist)
115
116 SYSINIT(posix_timer, SI_SUB_P1003_1B, SI_ORDER_FIRST+4, itimer_start, NULL);
117
118
119 static int
120 settime(struct thread *td, struct timeval *tv)
121 {
122         struct timeval delta, tv1, tv2;
123         static struct timeval maxtime, laststep;
124         struct timespec ts;
125
126         microtime(&tv1);
127         delta = *tv;
128         timevalsub(&delta, &tv1);
129
130         /*
131          * If the system is secure, we do not allow the time to be 
132          * set to a value earlier than 1 second less than the highest
133          * time we have yet seen. The worst a miscreant can do in
134          * this circumstance is "freeze" time. He couldn't go
135          * back to the past.
136          *
137          * We similarly do not allow the clock to be stepped more
138          * than one second, nor more than once per second. This allows
139          * a miscreant to make the clock march double-time, but no worse.
140          */
141         if (securelevel_gt(td->td_ucred, 1) != 0) {
142                 if (delta.tv_sec < 0 || delta.tv_usec < 0) {
143                         /*
144                          * Update maxtime to latest time we've seen.
145                          */
146                         if (tv1.tv_sec > maxtime.tv_sec)
147                                 maxtime = tv1;
148                         tv2 = *tv;
149                         timevalsub(&tv2, &maxtime);
150                         if (tv2.tv_sec < -1) {
151                                 tv->tv_sec = maxtime.tv_sec - 1;
152                                 printf("Time adjustment clamped to -1 second\n");
153                         }
154                 } else {
155                         if (tv1.tv_sec == laststep.tv_sec)
156                                 return (EPERM);
157                         if (delta.tv_sec > 1) {
158                                 tv->tv_sec = tv1.tv_sec + 1;
159                                 printf("Time adjustment clamped to +1 second\n");
160                         }
161                         laststep = *tv;
162                 }
163         }
164
165         ts.tv_sec = tv->tv_sec;
166         ts.tv_nsec = tv->tv_usec * 1000;
167         tc_setclock(&ts);
168         resettodr();
169         return (0);
170 }
171
172 #ifndef _SYS_SYSPROTO_H_
173 struct clock_getcpuclockid2_args {
174         id_t id;
175         int which,
176         clockid_t *clock_id;
177 };
178 #endif
179 /* ARGSUSED */
180 int
181 sys_clock_getcpuclockid2(struct thread *td, struct clock_getcpuclockid2_args *uap)
182 {
183         clockid_t clk_id;
184         int error;
185
186         error = kern_clock_getcpuclockid2(td, uap->id, uap->which, &clk_id);
187         if (error == 0)
188                 error = copyout(&clk_id, uap->clock_id, sizeof(clockid_t));
189         return (error);
190 }
191
192 int
193 kern_clock_getcpuclockid2(struct thread *td, id_t id, int which,
194     clockid_t *clk_id)
195 {
196         struct proc *p;
197         pid_t pid;
198         lwpid_t tid;
199         int error;
200
201         switch (which) {
202         case CPUCLOCK_WHICH_PID:
203                 if (id != 0) {
204                         error = pget(id, PGET_CANSEE | PGET_NOTID, &p);
205                         if (error != 0)
206                                 return (error);
207                         PROC_UNLOCK(p);
208                         pid = id;
209                 } else {
210                         pid = td->td_proc->p_pid;
211                 }
212                 *clk_id = MAKE_PROCESS_CPUCLOCK(pid);
213                 return (0);
214         case CPUCLOCK_WHICH_TID:
215                 tid = id == 0 ? td->td_tid : id;
216                 *clk_id = MAKE_THREAD_CPUCLOCK(tid);
217                 return (0);
218         default:
219                 return (EINVAL);
220         }
221 }
222
223 #ifndef _SYS_SYSPROTO_H_
224 struct clock_gettime_args {
225         clockid_t clock_id;
226         struct  timespec *tp;
227 };
228 #endif
229 /* ARGSUSED */
230 int
231 sys_clock_gettime(struct thread *td, struct clock_gettime_args *uap)
232 {
233         struct timespec ats;
234         int error;
235
236         error = kern_clock_gettime(td, uap->clock_id, &ats);
237         if (error == 0)
238                 error = copyout(&ats, uap->tp, sizeof(ats));
239
240         return (error);
241 }
242
243 static inline void
244 cputick2timespec(uint64_t runtime, struct timespec *ats)
245 {
246         runtime = cputick2usec(runtime);
247         ats->tv_sec = runtime / 1000000;
248         ats->tv_nsec = runtime % 1000000 * 1000;
249 }
250
251 void
252 kern_thread_cputime(struct thread *targettd, struct timespec *ats)
253 {
254         uint64_t runtime, curtime, switchtime;
255
256         if (targettd == NULL) { /* current thread */
257                 critical_enter();
258                 switchtime = PCPU_GET(switchtime);
259                 curtime = cpu_ticks();
260                 runtime = curthread->td_runtime;
261                 critical_exit();
262                 runtime += curtime - switchtime;
263         } else {
264                 PROC_LOCK_ASSERT(targettd->td_proc, MA_OWNED);
265                 thread_lock(targettd);
266                 runtime = targettd->td_runtime;
267                 thread_unlock(targettd);
268         }
269         cputick2timespec(runtime, ats);
270 }
271
272 void
273 kern_process_cputime(struct proc *targetp, struct timespec *ats)
274 {
275         uint64_t runtime;
276         struct rusage ru;
277
278         PROC_LOCK_ASSERT(targetp, MA_OWNED);
279         PROC_STATLOCK(targetp);
280         rufetch(targetp, &ru);
281         runtime = targetp->p_rux.rux_runtime;
282         if (curthread->td_proc == targetp)
283                 runtime += cpu_ticks() - PCPU_GET(switchtime);
284         PROC_STATUNLOCK(targetp);
285         cputick2timespec(runtime, ats);
286 }
287
288 static int
289 get_cputime(struct thread *td, clockid_t clock_id, struct timespec *ats)
290 {
291         struct proc *p, *p2;
292         struct thread *td2;
293         lwpid_t tid;
294         pid_t pid;
295         int error;
296
297         p = td->td_proc;
298         if ((clock_id & CPUCLOCK_PROCESS_BIT) == 0) {
299                 tid = clock_id & CPUCLOCK_ID_MASK;
300                 td2 = tdfind(tid, p->p_pid);
301                 if (td2 == NULL)
302                         return (EINVAL);
303                 kern_thread_cputime(td2, ats);
304                 PROC_UNLOCK(td2->td_proc);
305         } else {
306                 pid = clock_id & CPUCLOCK_ID_MASK;
307                 error = pget(pid, PGET_CANSEE, &p2);
308                 if (error != 0)
309                         return (EINVAL);
310                 kern_process_cputime(p2, ats);
311                 PROC_UNLOCK(p2);
312         }
313         return (0);
314 }
315
316 int
317 kern_clock_gettime(struct thread *td, clockid_t clock_id, struct timespec *ats)
318 {
319         struct timeval sys, user;
320         struct proc *p;
321
322         p = td->td_proc;
323         switch (clock_id) {
324         case CLOCK_REALTIME:            /* Default to precise. */
325         case CLOCK_REALTIME_PRECISE:
326                 nanotime(ats);
327                 break;
328         case CLOCK_REALTIME_FAST:
329                 getnanotime(ats);
330                 break;
331         case CLOCK_VIRTUAL:
332                 PROC_LOCK(p);
333                 PROC_STATLOCK(p);
334                 calcru(p, &user, &sys);
335                 PROC_STATUNLOCK(p);
336                 PROC_UNLOCK(p);
337                 TIMEVAL_TO_TIMESPEC(&user, ats);
338                 break;
339         case CLOCK_PROF:
340                 PROC_LOCK(p);
341                 PROC_STATLOCK(p);
342                 calcru(p, &user, &sys);
343                 PROC_STATUNLOCK(p);
344                 PROC_UNLOCK(p);
345                 timevaladd(&user, &sys);
346                 TIMEVAL_TO_TIMESPEC(&user, ats);
347                 break;
348         case CLOCK_MONOTONIC:           /* Default to precise. */
349         case CLOCK_MONOTONIC_PRECISE:
350         case CLOCK_UPTIME:
351         case CLOCK_UPTIME_PRECISE:
352                 nanouptime(ats);
353                 break;
354         case CLOCK_UPTIME_FAST:
355         case CLOCK_MONOTONIC_FAST:
356                 getnanouptime(ats);
357                 break;
358         case CLOCK_SECOND:
359                 ats->tv_sec = time_second;
360                 ats->tv_nsec = 0;
361                 break;
362         case CLOCK_THREAD_CPUTIME_ID:
363                 kern_thread_cputime(NULL, ats);
364                 break;
365         case CLOCK_PROCESS_CPUTIME_ID:
366                 PROC_LOCK(p);
367                 kern_process_cputime(p, ats);
368                 PROC_UNLOCK(p);
369                 break;
370         default:
371                 if ((int)clock_id >= 0)
372                         return (EINVAL);
373                 return (get_cputime(td, clock_id, ats));
374         }
375         return (0);
376 }
377
378 #ifndef _SYS_SYSPROTO_H_
379 struct clock_settime_args {
380         clockid_t clock_id;
381         const struct    timespec *tp;
382 };
383 #endif
384 /* ARGSUSED */
385 int
386 sys_clock_settime(struct thread *td, struct clock_settime_args *uap)
387 {
388         struct timespec ats;
389         int error;
390
391         if ((error = copyin(uap->tp, &ats, sizeof(ats))) != 0)
392                 return (error);
393         return (kern_clock_settime(td, uap->clock_id, &ats));
394 }
395
396 static int allow_insane_settime = 0;
397 SYSCTL_INT(_debug, OID_AUTO, allow_insane_settime, CTLFLAG_RWTUN,
398     &allow_insane_settime, 0,
399     "do not perform possibly restrictive checks on settime(2) args");
400
401 int
402 kern_clock_settime(struct thread *td, clockid_t clock_id, struct timespec *ats)
403 {
404         struct timeval atv;
405         int error;
406
407         if ((error = priv_check(td, PRIV_CLOCK_SETTIME)) != 0)
408                 return (error);
409         if (clock_id != CLOCK_REALTIME)
410                 return (EINVAL);
411         if (ats->tv_nsec < 0 || ats->tv_nsec >= 1000000000 ||
412             ats->tv_sec < 0)
413                 return (EINVAL);
414         if (!allow_insane_settime && ats->tv_sec > 8000ULL * 365 * 24 * 60 * 60)
415                 return (EINVAL);
416         /* XXX Don't convert nsec->usec and back */
417         TIMESPEC_TO_TIMEVAL(&atv, ats);
418         error = settime(td, &atv);
419         return (error);
420 }
421
422 #ifndef _SYS_SYSPROTO_H_
423 struct clock_getres_args {
424         clockid_t clock_id;
425         struct  timespec *tp;
426 };
427 #endif
428 int
429 sys_clock_getres(struct thread *td, struct clock_getres_args *uap)
430 {
431         struct timespec ts;
432         int error;
433
434         if (uap->tp == NULL)
435                 return (0);
436
437         error = kern_clock_getres(td, uap->clock_id, &ts);
438         if (error == 0)
439                 error = copyout(&ts, uap->tp, sizeof(ts));
440         return (error);
441 }
442
443 int
444 kern_clock_getres(struct thread *td, clockid_t clock_id, struct timespec *ts)
445 {
446
447         ts->tv_sec = 0;
448         switch (clock_id) {
449         case CLOCK_REALTIME:
450         case CLOCK_REALTIME_FAST:
451         case CLOCK_REALTIME_PRECISE:
452         case CLOCK_MONOTONIC:
453         case CLOCK_MONOTONIC_FAST:
454         case CLOCK_MONOTONIC_PRECISE:
455         case CLOCK_UPTIME:
456         case CLOCK_UPTIME_FAST:
457         case CLOCK_UPTIME_PRECISE:
458                 /*
459                  * Round up the result of the division cheaply by adding 1.
460                  * Rounding up is especially important if rounding down
461                  * would give 0.  Perfect rounding is unimportant.
462                  */
463                 ts->tv_nsec = 1000000000 / tc_getfrequency() + 1;
464                 break;
465         case CLOCK_VIRTUAL:
466         case CLOCK_PROF:
467                 /* Accurately round up here because we can do so cheaply. */
468                 ts->tv_nsec = howmany(1000000000, hz);
469                 break;
470         case CLOCK_SECOND:
471                 ts->tv_sec = 1;
472                 ts->tv_nsec = 0;
473                 break;
474         case CLOCK_THREAD_CPUTIME_ID:
475         case CLOCK_PROCESS_CPUTIME_ID:
476         cputime:
477                 /* sync with cputick2usec */
478                 ts->tv_nsec = 1000000 / cpu_tickrate();
479                 if (ts->tv_nsec == 0)
480                         ts->tv_nsec = 1000;
481                 break;
482         default:
483                 if ((int)clock_id < 0)
484                         goto cputime;
485                 return (EINVAL);
486         }
487         return (0);
488 }
489
490 int
491 kern_nanosleep(struct thread *td, struct timespec *rqt, struct timespec *rmt)
492 {
493
494         return (kern_clock_nanosleep(td, CLOCK_REALTIME, TIMER_RELTIME, rqt,
495             rmt));
496 }
497
498 static uint8_t nanowait[MAXCPU];
499
500 int
501 kern_clock_nanosleep(struct thread *td, clockid_t clock_id, int flags,
502     const struct timespec *rqt, struct timespec *rmt)
503 {
504         struct timespec ts, now;
505         sbintime_t sbt, sbtt, prec, tmp;
506         time_t over;
507         int error;
508         bool is_abs_real;
509
510         if (rqt->tv_nsec < 0 || rqt->tv_nsec >= 1000000000)
511                 return (EINVAL);
512         if ((flags & ~TIMER_ABSTIME) != 0)
513                 return (EINVAL);
514         switch (clock_id) {
515         case CLOCK_REALTIME:
516         case CLOCK_REALTIME_PRECISE:
517         case CLOCK_REALTIME_FAST:
518         case CLOCK_SECOND:
519                 is_abs_real = (flags & TIMER_ABSTIME) != 0;
520                 break;
521         case CLOCK_MONOTONIC:
522         case CLOCK_MONOTONIC_PRECISE:
523         case CLOCK_MONOTONIC_FAST:
524         case CLOCK_UPTIME:
525         case CLOCK_UPTIME_PRECISE:
526         case CLOCK_UPTIME_FAST:
527                 is_abs_real = false;
528                 break;
529         case CLOCK_VIRTUAL:
530         case CLOCK_PROF:
531         case CLOCK_PROCESS_CPUTIME_ID:
532                 return (ENOTSUP);
533         case CLOCK_THREAD_CPUTIME_ID:
534         default:
535                 return (EINVAL);
536         }
537         do {
538                 ts = *rqt;
539                 if ((flags & TIMER_ABSTIME) != 0) {
540                         if (is_abs_real)
541                                 td->td_rtcgen =
542                                     atomic_load_acq_int(&rtc_generation);
543                         error = kern_clock_gettime(td, clock_id, &now);
544                         KASSERT(error == 0, ("kern_clock_gettime: %d", error));
545                         timespecsub(&ts, &now, &ts);
546                 }
547                 if (ts.tv_sec < 0 || (ts.tv_sec == 0 && ts.tv_nsec == 0)) {
548                         error = EWOULDBLOCK;
549                         break;
550                 }
551                 if (ts.tv_sec > INT32_MAX / 2) {
552                         over = ts.tv_sec - INT32_MAX / 2;
553                         ts.tv_sec -= over;
554                 } else
555                         over = 0;
556                 tmp = tstosbt(ts);
557                 prec = tmp;
558                 prec >>= tc_precexp;
559                 if (TIMESEL(&sbt, tmp))
560                         sbt += tc_tick_sbt;
561                 sbt += tmp;
562                 error = tsleep_sbt(&nanowait[curcpu], PWAIT | PCATCH, "nanslp",
563                     sbt, prec, C_ABSOLUTE);
564         } while (error == 0 && is_abs_real && td->td_rtcgen == 0);
565         td->td_rtcgen = 0;
566         if (error != EWOULDBLOCK) {
567                 if (TIMESEL(&sbtt, tmp))
568                         sbtt += tc_tick_sbt;
569                 if (sbtt >= sbt)
570                         return (0);
571                 if (error == ERESTART)
572                         error = EINTR;
573                 if ((flags & TIMER_ABSTIME) == 0 && rmt != NULL) {
574                         ts = sbttots(sbt - sbtt);
575                         ts.tv_sec += over;
576                         if (ts.tv_sec < 0)
577                                 timespecclear(&ts);
578                         *rmt = ts;
579                 }
580                 return (error);
581         }
582         return (0);
583 }
584
585 #ifndef _SYS_SYSPROTO_H_
586 struct nanosleep_args {
587         struct  timespec *rqtp;
588         struct  timespec *rmtp;
589 };
590 #endif
591 /* ARGSUSED */
592 int
593 sys_nanosleep(struct thread *td, struct nanosleep_args *uap)
594 {
595
596         return (user_clock_nanosleep(td, CLOCK_REALTIME, TIMER_RELTIME,
597             uap->rqtp, uap->rmtp));
598 }
599
600 #ifndef _SYS_SYSPROTO_H_
601 struct clock_nanosleep_args {
602         clockid_t clock_id;
603         int       flags;
604         struct  timespec *rqtp;
605         struct  timespec *rmtp;
606 };
607 #endif
608 /* ARGSUSED */
609 int
610 sys_clock_nanosleep(struct thread *td, struct clock_nanosleep_args *uap)
611 {
612         int error;
613
614         error = user_clock_nanosleep(td, uap->clock_id, uap->flags, uap->rqtp,
615             uap->rmtp);
616         return (kern_posix_error(td, error));
617 }
618
619 static int
620 user_clock_nanosleep(struct thread *td, clockid_t clock_id, int flags,
621     const struct timespec *ua_rqtp, struct timespec *ua_rmtp)
622 {
623         struct timespec rmt, rqt;
624         int error, error2;
625
626         error = copyin(ua_rqtp, &rqt, sizeof(rqt));
627         if (error)
628                 return (error);
629         error = kern_clock_nanosleep(td, clock_id, flags, &rqt, &rmt);
630         if (error == EINTR && ua_rmtp != NULL && (flags & TIMER_ABSTIME) == 0) {
631                 error2 = copyout(&rmt, ua_rmtp, sizeof(rmt));
632                 if (error2 != 0)
633                         error = error2;
634         }
635         return (error);
636 }
637
638 #ifndef _SYS_SYSPROTO_H_
639 struct gettimeofday_args {
640         struct  timeval *tp;
641         struct  timezone *tzp;
642 };
643 #endif
644 /* ARGSUSED */
645 int
646 sys_gettimeofday(struct thread *td, struct gettimeofday_args *uap)
647 {
648         struct timeval atv;
649         struct timezone rtz;
650         int error = 0;
651
652         if (uap->tp) {
653                 microtime(&atv);
654                 error = copyout(&atv, uap->tp, sizeof (atv));
655         }
656         if (error == 0 && uap->tzp != NULL) {
657                 rtz.tz_minuteswest = tz_minuteswest;
658                 rtz.tz_dsttime = tz_dsttime;
659                 error = copyout(&rtz, uap->tzp, sizeof (rtz));
660         }
661         return (error);
662 }
663
664 #ifndef _SYS_SYSPROTO_H_
665 struct settimeofday_args {
666         struct  timeval *tv;
667         struct  timezone *tzp;
668 };
669 #endif
670 /* ARGSUSED */
671 int
672 sys_settimeofday(struct thread *td, struct settimeofday_args *uap)
673 {
674         struct timeval atv, *tvp;
675         struct timezone atz, *tzp;
676         int error;
677
678         if (uap->tv) {
679                 error = copyin(uap->tv, &atv, sizeof(atv));
680                 if (error)
681                         return (error);
682                 tvp = &atv;
683         } else
684                 tvp = NULL;
685         if (uap->tzp) {
686                 error = copyin(uap->tzp, &atz, sizeof(atz));
687                 if (error)
688                         return (error);
689                 tzp = &atz;
690         } else
691                 tzp = NULL;
692         return (kern_settimeofday(td, tvp, tzp));
693 }
694
695 int
696 kern_settimeofday(struct thread *td, struct timeval *tv, struct timezone *tzp)
697 {
698         int error;
699
700         error = priv_check(td, PRIV_SETTIMEOFDAY);
701         if (error)
702                 return (error);
703         /* Verify all parameters before changing time. */
704         if (tv) {
705                 if (tv->tv_usec < 0 || tv->tv_usec >= 1000000 ||
706                     tv->tv_sec < 0)
707                         return (EINVAL);
708                 error = settime(td, tv);
709         }
710         if (tzp && error == 0) {
711                 tz_minuteswest = tzp->tz_minuteswest;
712                 tz_dsttime = tzp->tz_dsttime;
713         }
714         return (error);
715 }
716
717 /*
718  * Get value of an interval timer.  The process virtual and profiling virtual
719  * time timers are kept in the p_stats area, since they can be swapped out.
720  * These are kept internally in the way they are specified externally: in
721  * time until they expire.
722  *
723  * The real time interval timer is kept in the process table slot for the
724  * process, and its value (it_value) is kept as an absolute time rather than
725  * as a delta, so that it is easy to keep periodic real-time signals from
726  * drifting.
727  *
728  * Virtual time timers are processed in the hardclock() routine of
729  * kern_clock.c.  The real time timer is processed by a timeout routine,
730  * called from the softclock() routine.  Since a callout may be delayed in
731  * real time due to interrupt processing in the system, it is possible for
732  * the real time timeout routine (realitexpire, given below), to be delayed
733  * in real time past when it is supposed to occur.  It does not suffice,
734  * therefore, to reload the real timer .it_value from the real time timers
735  * .it_interval.  Rather, we compute the next time in absolute time the timer
736  * should go off.
737  */
738 #ifndef _SYS_SYSPROTO_H_
739 struct getitimer_args {
740         u_int   which;
741         struct  itimerval *itv;
742 };
743 #endif
744 int
745 sys_getitimer(struct thread *td, struct getitimer_args *uap)
746 {
747         struct itimerval aitv;
748         int error;
749
750         error = kern_getitimer(td, uap->which, &aitv);
751         if (error != 0)
752                 return (error);
753         return (copyout(&aitv, uap->itv, sizeof (struct itimerval)));
754 }
755
756 int
757 kern_getitimer(struct thread *td, u_int which, struct itimerval *aitv)
758 {
759         struct proc *p = td->td_proc;
760         struct timeval ctv;
761
762         if (which > ITIMER_PROF)
763                 return (EINVAL);
764
765         if (which == ITIMER_REAL) {
766                 /*
767                  * Convert from absolute to relative time in .it_value
768                  * part of real time timer.  If time for real time timer
769                  * has passed return 0, else return difference between
770                  * current time and time for the timer to go off.
771                  */
772                 PROC_LOCK(p);
773                 *aitv = p->p_realtimer;
774                 PROC_UNLOCK(p);
775                 if (timevalisset(&aitv->it_value)) {
776                         microuptime(&ctv);
777                         if (timevalcmp(&aitv->it_value, &ctv, <))
778                                 timevalclear(&aitv->it_value);
779                         else
780                                 timevalsub(&aitv->it_value, &ctv);
781                 }
782         } else {
783                 PROC_ITIMLOCK(p);
784                 *aitv = p->p_stats->p_timer[which];
785                 PROC_ITIMUNLOCK(p);
786         }
787 #ifdef KTRACE
788         if (KTRPOINT(td, KTR_STRUCT))
789                 ktritimerval(aitv);
790 #endif
791         return (0);
792 }
793
794 #ifndef _SYS_SYSPROTO_H_
795 struct setitimer_args {
796         u_int   which;
797         struct  itimerval *itv, *oitv;
798 };
799 #endif
800 int
801 sys_setitimer(struct thread *td, struct setitimer_args *uap)
802 {
803         struct itimerval aitv, oitv;
804         int error;
805
806         if (uap->itv == NULL) {
807                 uap->itv = uap->oitv;
808                 return (sys_getitimer(td, (struct getitimer_args *)uap));
809         }
810
811         if ((error = copyin(uap->itv, &aitv, sizeof(struct itimerval))))
812                 return (error);
813         error = kern_setitimer(td, uap->which, &aitv, &oitv);
814         if (error != 0 || uap->oitv == NULL)
815                 return (error);
816         return (copyout(&oitv, uap->oitv, sizeof(struct itimerval)));
817 }
818
819 int
820 kern_setitimer(struct thread *td, u_int which, struct itimerval *aitv,
821     struct itimerval *oitv)
822 {
823         struct proc *p = td->td_proc;
824         struct timeval ctv;
825         sbintime_t sbt, pr;
826
827         if (aitv == NULL)
828                 return (kern_getitimer(td, which, oitv));
829
830         if (which > ITIMER_PROF)
831                 return (EINVAL);
832 #ifdef KTRACE
833         if (KTRPOINT(td, KTR_STRUCT))
834                 ktritimerval(aitv);
835 #endif
836         if (itimerfix(&aitv->it_value) ||
837             aitv->it_value.tv_sec > INT32_MAX / 2)
838                 return (EINVAL);
839         if (!timevalisset(&aitv->it_value))
840                 timevalclear(&aitv->it_interval);
841         else if (itimerfix(&aitv->it_interval) ||
842             aitv->it_interval.tv_sec > INT32_MAX / 2)
843                 return (EINVAL);
844
845         if (which == ITIMER_REAL) {
846                 PROC_LOCK(p);
847                 if (timevalisset(&p->p_realtimer.it_value))
848                         callout_stop(&p->p_itcallout);
849                 microuptime(&ctv);
850                 if (timevalisset(&aitv->it_value)) {
851                         pr = tvtosbt(aitv->it_value) >> tc_precexp;
852                         timevaladd(&aitv->it_value, &ctv);
853                         sbt = tvtosbt(aitv->it_value);
854                         callout_reset_sbt(&p->p_itcallout, sbt, pr,
855                             realitexpire, p, C_ABSOLUTE);
856                 }
857                 *oitv = p->p_realtimer;
858                 p->p_realtimer = *aitv;
859                 PROC_UNLOCK(p);
860                 if (timevalisset(&oitv->it_value)) {
861                         if (timevalcmp(&oitv->it_value, &ctv, <))
862                                 timevalclear(&oitv->it_value);
863                         else
864                                 timevalsub(&oitv->it_value, &ctv);
865                 }
866         } else {
867                 if (aitv->it_interval.tv_sec == 0 &&
868                     aitv->it_interval.tv_usec != 0 &&
869                     aitv->it_interval.tv_usec < tick)
870                         aitv->it_interval.tv_usec = tick;
871                 if (aitv->it_value.tv_sec == 0 &&
872                     aitv->it_value.tv_usec != 0 &&
873                     aitv->it_value.tv_usec < tick)
874                         aitv->it_value.tv_usec = tick;
875                 PROC_ITIMLOCK(p);
876                 *oitv = p->p_stats->p_timer[which];
877                 p->p_stats->p_timer[which] = *aitv;
878                 PROC_ITIMUNLOCK(p);
879         }
880 #ifdef KTRACE
881         if (KTRPOINT(td, KTR_STRUCT))
882                 ktritimerval(oitv);
883 #endif
884         return (0);
885 }
886
887 /*
888  * Real interval timer expired:
889  * send process whose timer expired an alarm signal.
890  * If time is not set up to reload, then just return.
891  * Else compute next time timer should go off which is > current time.
892  * This is where delay in processing this timeout causes multiple
893  * SIGALRM calls to be compressed into one.
894  * tvtohz() always adds 1 to allow for the time until the next clock
895  * interrupt being strictly less than 1 clock tick, but we don't want
896  * that here since we want to appear to be in sync with the clock
897  * interrupt even when we're delayed.
898  */
899 void
900 realitexpire(void *arg)
901 {
902         struct proc *p;
903         struct timeval ctv;
904         sbintime_t isbt;
905
906         p = (struct proc *)arg;
907         kern_psignal(p, SIGALRM);
908         if (!timevalisset(&p->p_realtimer.it_interval)) {
909                 timevalclear(&p->p_realtimer.it_value);
910                 if (p->p_flag & P_WEXIT)
911                         wakeup(&p->p_itcallout);
912                 return;
913         }
914         isbt = tvtosbt(p->p_realtimer.it_interval);
915         if (isbt >= sbt_timethreshold)
916                 getmicrouptime(&ctv);
917         else
918                 microuptime(&ctv);
919         do {
920                 timevaladd(&p->p_realtimer.it_value,
921                     &p->p_realtimer.it_interval);
922         } while (timevalcmp(&p->p_realtimer.it_value, &ctv, <=));
923         callout_reset_sbt(&p->p_itcallout, tvtosbt(p->p_realtimer.it_value),
924             isbt >> tc_precexp, realitexpire, p, C_ABSOLUTE);
925 }
926
927 /*
928  * Check that a proposed value to load into the .it_value or
929  * .it_interval part of an interval timer is acceptable, and
930  * fix it to have at least minimal value (i.e. if it is less
931  * than the resolution of the clock, round it up.)
932  */
933 int
934 itimerfix(struct timeval *tv)
935 {
936
937         if (tv->tv_sec < 0 || tv->tv_usec < 0 || tv->tv_usec >= 1000000)
938                 return (EINVAL);
939         if (tv->tv_sec == 0 && tv->tv_usec != 0 &&
940             tv->tv_usec < (u_int)tick / 16)
941                 tv->tv_usec = (u_int)tick / 16;
942         return (0);
943 }
944
945 /*
946  * Decrement an interval timer by a specified number
947  * of microseconds, which must be less than a second,
948  * i.e. < 1000000.  If the timer expires, then reload
949  * it.  In this case, carry over (usec - old value) to
950  * reduce the value reloaded into the timer so that
951  * the timer does not drift.  This routine assumes
952  * that it is called in a context where the timers
953  * on which it is operating cannot change in value.
954  */
955 int
956 itimerdecr(struct itimerval *itp, int usec)
957 {
958
959         if (itp->it_value.tv_usec < usec) {
960                 if (itp->it_value.tv_sec == 0) {
961                         /* expired, and already in next interval */
962                         usec -= itp->it_value.tv_usec;
963                         goto expire;
964                 }
965                 itp->it_value.tv_usec += 1000000;
966                 itp->it_value.tv_sec--;
967         }
968         itp->it_value.tv_usec -= usec;
969         usec = 0;
970         if (timevalisset(&itp->it_value))
971                 return (1);
972         /* expired, exactly at end of interval */
973 expire:
974         if (timevalisset(&itp->it_interval)) {
975                 itp->it_value = itp->it_interval;
976                 itp->it_value.tv_usec -= usec;
977                 if (itp->it_value.tv_usec < 0) {
978                         itp->it_value.tv_usec += 1000000;
979                         itp->it_value.tv_sec--;
980                 }
981         } else
982                 itp->it_value.tv_usec = 0;              /* sec is already 0 */
983         return (0);
984 }
985
986 /*
987  * Add and subtract routines for timevals.
988  * N.B.: subtract routine doesn't deal with
989  * results which are before the beginning,
990  * it just gets very confused in this case.
991  * Caveat emptor.
992  */
993 void
994 timevaladd(struct timeval *t1, const struct timeval *t2)
995 {
996
997         t1->tv_sec += t2->tv_sec;
998         t1->tv_usec += t2->tv_usec;
999         timevalfix(t1);
1000 }
1001
1002 void
1003 timevalsub(struct timeval *t1, const struct timeval *t2)
1004 {
1005
1006         t1->tv_sec -= t2->tv_sec;
1007         t1->tv_usec -= t2->tv_usec;
1008         timevalfix(t1);
1009 }
1010
1011 static void
1012 timevalfix(struct timeval *t1)
1013 {
1014
1015         if (t1->tv_usec < 0) {
1016                 t1->tv_sec--;
1017                 t1->tv_usec += 1000000;
1018         }
1019         if (t1->tv_usec >= 1000000) {
1020                 t1->tv_sec++;
1021                 t1->tv_usec -= 1000000;
1022         }
1023 }
1024
1025 /*
1026  * ratecheck(): simple time-based rate-limit checking.
1027  */
1028 int
1029 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
1030 {
1031         struct timeval tv, delta;
1032         int rv = 0;
1033
1034         getmicrouptime(&tv);            /* NB: 10ms precision */
1035         delta = tv;
1036         timevalsub(&delta, lasttime);
1037
1038         /*
1039          * check for 0,0 is so that the message will be seen at least once,
1040          * even if interval is huge.
1041          */
1042         if (timevalcmp(&delta, mininterval, >=) ||
1043             (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
1044                 *lasttime = tv;
1045                 rv = 1;
1046         }
1047
1048         return (rv);
1049 }
1050
1051 /*
1052  * ppsratecheck(): packets (or events) per second limitation.
1053  *
1054  * Return 0 if the limit is to be enforced (e.g. the caller
1055  * should drop a packet because of the rate limitation).
1056  *
1057  * maxpps of 0 always causes zero to be returned.  maxpps of -1
1058  * always causes 1 to be returned; this effectively defeats rate
1059  * limiting.
1060  *
1061  * Note that we maintain the struct timeval for compatibility
1062  * with other bsd systems.  We reuse the storage and just monitor
1063  * clock ticks for minimal overhead.  
1064  */
1065 int
1066 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
1067 {
1068         int now;
1069
1070         /*
1071          * Reset the last time and counter if this is the first call
1072          * or more than a second has passed since the last update of
1073          * lasttime.
1074          */
1075         now = ticks;
1076         if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
1077                 lasttime->tv_sec = now;
1078                 *curpps = 1;
1079                 return (maxpps != 0);
1080         } else {
1081                 (*curpps)++;            /* NB: ignore potential overflow */
1082                 return (maxpps < 0 || *curpps <= maxpps);
1083         }
1084 }
1085
1086 static void
1087 itimer_start(void)
1088 {
1089         static const struct kclock rt_clock = {
1090                 .timer_create  = realtimer_create,
1091                 .timer_delete  = realtimer_delete,
1092                 .timer_settime = realtimer_settime,
1093                 .timer_gettime = realtimer_gettime,
1094         };
1095
1096         itimer_zone = uma_zcreate("itimer", sizeof(struct itimer),
1097                 NULL, NULL, itimer_init, itimer_fini, UMA_ALIGN_PTR, 0);
1098         register_posix_clock(CLOCK_REALTIME,  &rt_clock);
1099         register_posix_clock(CLOCK_MONOTONIC, &rt_clock);
1100         p31b_setcfg(CTL_P1003_1B_TIMERS, 200112L);
1101         p31b_setcfg(CTL_P1003_1B_DELAYTIMER_MAX, INT_MAX);
1102         p31b_setcfg(CTL_P1003_1B_TIMER_MAX, TIMER_MAX);
1103 }
1104
1105 static int
1106 register_posix_clock(int clockid, const struct kclock *clk)
1107 {
1108         if ((unsigned)clockid >= MAX_CLOCKS) {
1109                 printf("%s: invalid clockid\n", __func__);
1110                 return (0);
1111         }
1112         posix_clocks[clockid] = *clk;
1113         return (1);
1114 }
1115
1116 static int
1117 itimer_init(void *mem, int size, int flags)
1118 {
1119         struct itimer *it;
1120
1121         it = (struct itimer *)mem;
1122         mtx_init(&it->it_mtx, "itimer lock", NULL, MTX_DEF);
1123         return (0);
1124 }
1125
1126 static void
1127 itimer_fini(void *mem, int size)
1128 {
1129         struct itimer *it;
1130
1131         it = (struct itimer *)mem;
1132         mtx_destroy(&it->it_mtx);
1133 }
1134
1135 static void
1136 itimer_enter(struct itimer *it)
1137 {
1138
1139         mtx_assert(&it->it_mtx, MA_OWNED);
1140         it->it_usecount++;
1141 }
1142
1143 static void
1144 itimer_leave(struct itimer *it)
1145 {
1146
1147         mtx_assert(&it->it_mtx, MA_OWNED);
1148         KASSERT(it->it_usecount > 0, ("invalid it_usecount"));
1149
1150         if (--it->it_usecount == 0 && (it->it_flags & ITF_WANTED) != 0)
1151                 wakeup(it);
1152 }
1153
1154 #ifndef _SYS_SYSPROTO_H_
1155 struct ktimer_create_args {
1156         clockid_t clock_id;
1157         struct sigevent * evp;
1158         int * timerid;
1159 };
1160 #endif
1161 int
1162 sys_ktimer_create(struct thread *td, struct ktimer_create_args *uap)
1163 {
1164         struct sigevent *evp, ev;
1165         int id;
1166         int error;
1167
1168         if (uap->evp == NULL) {
1169                 evp = NULL;
1170         } else {
1171                 error = copyin(uap->evp, &ev, sizeof(ev));
1172                 if (error != 0)
1173                         return (error);
1174                 evp = &ev;
1175         }
1176         error = kern_ktimer_create(td, uap->clock_id, evp, &id, -1);
1177         if (error == 0) {
1178                 error = copyout(&id, uap->timerid, sizeof(int));
1179                 if (error != 0)
1180                         kern_ktimer_delete(td, id);
1181         }
1182         return (error);
1183 }
1184
1185 int
1186 kern_ktimer_create(struct thread *td, clockid_t clock_id, struct sigevent *evp,
1187     int *timerid, int preset_id)
1188 {
1189         struct proc *p = td->td_proc;
1190         struct itimer *it;
1191         int id;
1192         int error;
1193
1194         if (clock_id < 0 || clock_id >= MAX_CLOCKS)
1195                 return (EINVAL);
1196
1197         if (posix_clocks[clock_id].timer_create == NULL)
1198                 return (EINVAL);
1199
1200         if (evp != NULL) {
1201                 if (evp->sigev_notify != SIGEV_NONE &&
1202                     evp->sigev_notify != SIGEV_SIGNAL &&
1203                     evp->sigev_notify != SIGEV_THREAD_ID)
1204                         return (EINVAL);
1205                 if ((evp->sigev_notify == SIGEV_SIGNAL ||
1206                      evp->sigev_notify == SIGEV_THREAD_ID) &&
1207                         !_SIG_VALID(evp->sigev_signo))
1208                         return (EINVAL);
1209         }
1210         
1211         if (p->p_itimers == NULL)
1212                 itimers_alloc(p);
1213         
1214         it = uma_zalloc(itimer_zone, M_WAITOK);
1215         it->it_flags = 0;
1216         it->it_usecount = 0;
1217         it->it_active = 0;
1218         timespecclear(&it->it_time.it_value);
1219         timespecclear(&it->it_time.it_interval);
1220         it->it_overrun = 0;
1221         it->it_overrun_last = 0;
1222         it->it_clockid = clock_id;
1223         it->it_timerid = -1;
1224         it->it_proc = p;
1225         ksiginfo_init(&it->it_ksi);
1226         it->it_ksi.ksi_flags |= KSI_INS | KSI_EXT;
1227         error = CLOCK_CALL(clock_id, timer_create, (it));
1228         if (error != 0)
1229                 goto out;
1230
1231         PROC_LOCK(p);
1232         if (preset_id != -1) {
1233                 KASSERT(preset_id >= 0 && preset_id < 3, ("invalid preset_id"));
1234                 id = preset_id;
1235                 if (p->p_itimers->its_timers[id] != NULL) {
1236                         PROC_UNLOCK(p);
1237                         error = 0;
1238                         goto out;
1239                 }
1240         } else {
1241                 /*
1242                  * Find a free timer slot, skipping those reserved
1243                  * for setitimer().
1244                  */
1245                 for (id = 3; id < TIMER_MAX; id++)
1246                         if (p->p_itimers->its_timers[id] == NULL)
1247                                 break;
1248                 if (id == TIMER_MAX) {
1249                         PROC_UNLOCK(p);
1250                         error = EAGAIN;
1251                         goto out;
1252                 }
1253         }
1254         it->it_timerid = id;
1255         p->p_itimers->its_timers[id] = it;
1256         if (evp != NULL)
1257                 it->it_sigev = *evp;
1258         else {
1259                 it->it_sigev.sigev_notify = SIGEV_SIGNAL;
1260                 switch (clock_id) {
1261                 default:
1262                 case CLOCK_REALTIME:
1263                         it->it_sigev.sigev_signo = SIGALRM;
1264                         break;
1265                 case CLOCK_VIRTUAL:
1266                         it->it_sigev.sigev_signo = SIGVTALRM;
1267                         break;
1268                 case CLOCK_PROF:
1269                         it->it_sigev.sigev_signo = SIGPROF;
1270                         break;
1271                 }
1272                 it->it_sigev.sigev_value.sival_int = id;
1273         }
1274
1275         if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1276             it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1277                 it->it_ksi.ksi_signo = it->it_sigev.sigev_signo;
1278                 it->it_ksi.ksi_code = SI_TIMER;
1279                 it->it_ksi.ksi_value = it->it_sigev.sigev_value;
1280                 it->it_ksi.ksi_timerid = id;
1281         }
1282         PROC_UNLOCK(p);
1283         *timerid = id;
1284         return (0);
1285
1286 out:
1287         ITIMER_LOCK(it);
1288         CLOCK_CALL(it->it_clockid, timer_delete, (it));
1289         ITIMER_UNLOCK(it);
1290         uma_zfree(itimer_zone, it);
1291         return (error);
1292 }
1293
1294 #ifndef _SYS_SYSPROTO_H_
1295 struct ktimer_delete_args {
1296         int timerid;
1297 };
1298 #endif
1299 int
1300 sys_ktimer_delete(struct thread *td, struct ktimer_delete_args *uap)
1301 {
1302
1303         return (kern_ktimer_delete(td, uap->timerid));
1304 }
1305
1306 static struct itimer *
1307 itimer_find(struct proc *p, int timerid)
1308 {
1309         struct itimer *it;
1310
1311         PROC_LOCK_ASSERT(p, MA_OWNED);
1312         if ((p->p_itimers == NULL) ||
1313             (timerid < 0) || (timerid >= TIMER_MAX) ||
1314             (it = p->p_itimers->its_timers[timerid]) == NULL) {
1315                 return (NULL);
1316         }
1317         ITIMER_LOCK(it);
1318         if ((it->it_flags & ITF_DELETING) != 0) {
1319                 ITIMER_UNLOCK(it);
1320                 it = NULL;
1321         }
1322         return (it);
1323 }
1324
1325 int
1326 kern_ktimer_delete(struct thread *td, int timerid)
1327 {
1328         struct proc *p = td->td_proc;
1329         struct itimer *it;
1330
1331         PROC_LOCK(p);
1332         it = itimer_find(p, timerid);
1333         if (it == NULL) {
1334                 PROC_UNLOCK(p);
1335                 return (EINVAL);
1336         }
1337         PROC_UNLOCK(p);
1338
1339         it->it_flags |= ITF_DELETING;
1340         while (it->it_usecount > 0) {
1341                 it->it_flags |= ITF_WANTED;
1342                 msleep(it, &it->it_mtx, PPAUSE, "itimer", 0);
1343         }
1344         it->it_flags &= ~ITF_WANTED;
1345         CLOCK_CALL(it->it_clockid, timer_delete, (it));
1346         ITIMER_UNLOCK(it);
1347
1348         PROC_LOCK(p);
1349         if (KSI_ONQ(&it->it_ksi))
1350                 sigqueue_take(&it->it_ksi);
1351         p->p_itimers->its_timers[timerid] = NULL;
1352         PROC_UNLOCK(p);
1353         uma_zfree(itimer_zone, it);
1354         return (0);
1355 }
1356
1357 #ifndef _SYS_SYSPROTO_H_
1358 struct ktimer_settime_args {
1359         int timerid;
1360         int flags;
1361         const struct itimerspec * value;
1362         struct itimerspec * ovalue;
1363 };
1364 #endif
1365 int
1366 sys_ktimer_settime(struct thread *td, struct ktimer_settime_args *uap)
1367 {
1368         struct itimerspec val, oval, *ovalp;
1369         int error;
1370
1371         error = copyin(uap->value, &val, sizeof(val));
1372         if (error != 0)
1373                 return (error);
1374         ovalp = uap->ovalue != NULL ? &oval : NULL;
1375         error = kern_ktimer_settime(td, uap->timerid, uap->flags, &val, ovalp);
1376         if (error == 0 && uap->ovalue != NULL)
1377                 error = copyout(ovalp, uap->ovalue, sizeof(*ovalp));
1378         return (error);
1379 }
1380
1381 int
1382 kern_ktimer_settime(struct thread *td, int timer_id, int flags,
1383     struct itimerspec *val, struct itimerspec *oval)
1384 {
1385         struct proc *p;
1386         struct itimer *it;
1387         int error;
1388
1389         p = td->td_proc;
1390         PROC_LOCK(p);
1391         if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1392                 PROC_UNLOCK(p);
1393                 error = EINVAL;
1394         } else {
1395                 PROC_UNLOCK(p);
1396                 itimer_enter(it);
1397                 error = CLOCK_CALL(it->it_clockid, timer_settime, (it,
1398                     flags, val, oval));
1399                 itimer_leave(it);
1400                 ITIMER_UNLOCK(it);
1401         }
1402         return (error);
1403 }
1404
1405 #ifndef _SYS_SYSPROTO_H_
1406 struct ktimer_gettime_args {
1407         int timerid;
1408         struct itimerspec * value;
1409 };
1410 #endif
1411 int
1412 sys_ktimer_gettime(struct thread *td, struct ktimer_gettime_args *uap)
1413 {
1414         struct itimerspec val;
1415         int error;
1416
1417         error = kern_ktimer_gettime(td, uap->timerid, &val);
1418         if (error == 0)
1419                 error = copyout(&val, uap->value, sizeof(val));
1420         return (error);
1421 }
1422
1423 int
1424 kern_ktimer_gettime(struct thread *td, int timer_id, struct itimerspec *val)
1425 {
1426         struct proc *p;
1427         struct itimer *it;
1428         int error;
1429
1430         p = td->td_proc;
1431         PROC_LOCK(p);
1432         if (timer_id < 3 || (it = itimer_find(p, timer_id)) == NULL) {
1433                 PROC_UNLOCK(p);
1434                 error = EINVAL;
1435         } else {
1436                 PROC_UNLOCK(p);
1437                 itimer_enter(it);
1438                 error = CLOCK_CALL(it->it_clockid, timer_gettime, (it, val));
1439                 itimer_leave(it);
1440                 ITIMER_UNLOCK(it);
1441         }
1442         return (error);
1443 }
1444
1445 #ifndef _SYS_SYSPROTO_H_
1446 struct timer_getoverrun_args {
1447         int timerid;
1448 };
1449 #endif
1450 int
1451 sys_ktimer_getoverrun(struct thread *td, struct ktimer_getoverrun_args *uap)
1452 {
1453
1454         return (kern_ktimer_getoverrun(td, uap->timerid));
1455 }
1456
1457 int
1458 kern_ktimer_getoverrun(struct thread *td, int timer_id)
1459 {
1460         struct proc *p = td->td_proc;
1461         struct itimer *it;
1462         int error ;
1463
1464         PROC_LOCK(p);
1465         if (timer_id < 3 ||
1466             (it = itimer_find(p, timer_id)) == NULL) {
1467                 PROC_UNLOCK(p);
1468                 error = EINVAL;
1469         } else {
1470                 td->td_retval[0] = it->it_overrun_last;
1471                 ITIMER_UNLOCK(it);
1472                 PROC_UNLOCK(p);
1473                 error = 0;
1474         }
1475         return (error);
1476 }
1477
1478 static int
1479 realtimer_create(struct itimer *it)
1480 {
1481         callout_init_mtx(&it->it_callout, &it->it_mtx, 0);
1482         return (0);
1483 }
1484
1485 static int
1486 realtimer_delete(struct itimer *it)
1487 {
1488         mtx_assert(&it->it_mtx, MA_OWNED);
1489         
1490         /*
1491          * clear timer's value and interval to tell realtimer_expire
1492          * to not rearm the timer.
1493          */
1494         timespecclear(&it->it_time.it_value);
1495         timespecclear(&it->it_time.it_interval);
1496         ITIMER_UNLOCK(it);
1497         callout_drain(&it->it_callout);
1498         ITIMER_LOCK(it);
1499         return (0);
1500 }
1501
1502 static int
1503 realtimer_gettime(struct itimer *it, struct itimerspec *ovalue)
1504 {
1505         struct timespec cts;
1506
1507         mtx_assert(&it->it_mtx, MA_OWNED);
1508
1509         realtimer_clocktime(it->it_clockid, &cts);
1510         *ovalue = it->it_time;
1511         if (ovalue->it_value.tv_sec != 0 || ovalue->it_value.tv_nsec != 0) {
1512                 timespecsub(&ovalue->it_value, &cts, &ovalue->it_value);
1513                 if (ovalue->it_value.tv_sec < 0 ||
1514                     (ovalue->it_value.tv_sec == 0 &&
1515                      ovalue->it_value.tv_nsec == 0)) {
1516                         ovalue->it_value.tv_sec  = 0;
1517                         ovalue->it_value.tv_nsec = 1;
1518                 }
1519         }
1520         return (0);
1521 }
1522
1523 static int
1524 realtimer_settime(struct itimer *it, int flags,
1525         struct itimerspec *value, struct itimerspec *ovalue)
1526 {
1527         struct timespec cts, ts;
1528         struct timeval tv;
1529         struct itimerspec val;
1530
1531         mtx_assert(&it->it_mtx, MA_OWNED);
1532
1533         val = *value;
1534         if (itimespecfix(&val.it_value))
1535                 return (EINVAL);
1536
1537         if (timespecisset(&val.it_value)) {
1538                 if (itimespecfix(&val.it_interval))
1539                         return (EINVAL);
1540         } else {
1541                 timespecclear(&val.it_interval);
1542         }
1543         
1544         if (ovalue != NULL)
1545                 realtimer_gettime(it, ovalue);
1546
1547         it->it_time = val;
1548         if (timespecisset(&val.it_value)) {
1549                 realtimer_clocktime(it->it_clockid, &cts);
1550                 ts = val.it_value;
1551                 if ((flags & TIMER_ABSTIME) == 0) {
1552                         /* Convert to absolute time. */
1553                         timespecadd(&it->it_time.it_value, &cts,
1554                                 &it->it_time.it_value);
1555                 } else {
1556                         timespecsub(&ts, &cts, &ts);
1557                         /*
1558                          * We don't care if ts is negative, tztohz will
1559                          * fix it.
1560                          */
1561                 }
1562                 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1563                 callout_reset(&it->it_callout, tvtohz(&tv),
1564                         realtimer_expire, it);
1565         } else {
1566                 callout_stop(&it->it_callout);
1567         }
1568
1569         return (0);
1570 }
1571
1572 static void
1573 realtimer_clocktime(clockid_t id, struct timespec *ts)
1574 {
1575         if (id == CLOCK_REALTIME)
1576                 getnanotime(ts);
1577         else    /* CLOCK_MONOTONIC */
1578                 getnanouptime(ts);
1579 }
1580
1581 int
1582 itimer_accept(struct proc *p, int timerid, ksiginfo_t *ksi)
1583 {
1584         struct itimer *it;
1585
1586         PROC_LOCK_ASSERT(p, MA_OWNED);
1587         it = itimer_find(p, timerid);
1588         if (it != NULL) {
1589                 ksi->ksi_overrun = it->it_overrun;
1590                 it->it_overrun_last = it->it_overrun;
1591                 it->it_overrun = 0;
1592                 ITIMER_UNLOCK(it);
1593                 return (0);
1594         }
1595         return (EINVAL);
1596 }
1597
1598 int
1599 itimespecfix(struct timespec *ts)
1600 {
1601
1602         if (ts->tv_sec < 0 || ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000)
1603                 return (EINVAL);
1604         if (ts->tv_sec == 0 && ts->tv_nsec != 0 && ts->tv_nsec < tick * 1000)
1605                 ts->tv_nsec = tick * 1000;
1606         return (0);
1607 }
1608
1609 /* Timeout callback for realtime timer */
1610 static void
1611 realtimer_expire(void *arg)
1612 {
1613         struct timespec cts, ts;
1614         struct timeval tv;
1615         struct itimer *it;
1616
1617         it = (struct itimer *)arg;
1618
1619         realtimer_clocktime(it->it_clockid, &cts);
1620         /* Only fire if time is reached. */
1621         if (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1622                 if (timespecisset(&it->it_time.it_interval)) {
1623                         timespecadd(&it->it_time.it_value,
1624                                     &it->it_time.it_interval,
1625                                     &it->it_time.it_value);
1626                         while (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1627                                 if (it->it_overrun < INT_MAX)
1628                                         it->it_overrun++;
1629                                 else
1630                                         it->it_ksi.ksi_errno = ERANGE;
1631                                 timespecadd(&it->it_time.it_value,
1632                                             &it->it_time.it_interval,
1633                                             &it->it_time.it_value);
1634                         }
1635                 } else {
1636                         /* single shot timer ? */
1637                         timespecclear(&it->it_time.it_value);
1638                 }
1639                 if (timespecisset(&it->it_time.it_value)) {
1640                         timespecsub(&it->it_time.it_value, &cts, &ts);
1641                         TIMESPEC_TO_TIMEVAL(&tv, &ts);
1642                         callout_reset(&it->it_callout, tvtohz(&tv),
1643                                  realtimer_expire, it);
1644                 }
1645                 itimer_enter(it);
1646                 ITIMER_UNLOCK(it);
1647                 itimer_fire(it);
1648                 ITIMER_LOCK(it);
1649                 itimer_leave(it);
1650         } else if (timespecisset(&it->it_time.it_value)) {
1651                 ts = it->it_time.it_value;
1652                 timespecsub(&ts, &cts, &ts);
1653                 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1654                 callout_reset(&it->it_callout, tvtohz(&tv), realtimer_expire,
1655                         it);
1656         }
1657 }
1658
1659 void
1660 itimer_fire(struct itimer *it)
1661 {
1662         struct proc *p = it->it_proc;
1663         struct thread *td;
1664
1665         if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1666             it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1667                 if (sigev_findtd(p, &it->it_sigev, &td) != 0) {
1668                         ITIMER_LOCK(it);
1669                         timespecclear(&it->it_time.it_value);
1670                         timespecclear(&it->it_time.it_interval);
1671                         callout_stop(&it->it_callout);
1672                         ITIMER_UNLOCK(it);
1673                         return;
1674                 }
1675                 if (!KSI_ONQ(&it->it_ksi)) {
1676                         it->it_ksi.ksi_errno = 0;
1677                         ksiginfo_set_sigev(&it->it_ksi, &it->it_sigev);
1678                         tdsendsignal(p, td, it->it_ksi.ksi_signo, &it->it_ksi);
1679                 } else {
1680                         if (it->it_overrun < INT_MAX)
1681                                 it->it_overrun++;
1682                         else
1683                                 it->it_ksi.ksi_errno = ERANGE;
1684                 }
1685                 PROC_UNLOCK(p);
1686         }
1687 }
1688
1689 static void
1690 itimers_alloc(struct proc *p)
1691 {
1692         struct itimers *its;
1693         int i;
1694
1695         its = malloc(sizeof (struct itimers), M_SUBPROC, M_WAITOK | M_ZERO);
1696         LIST_INIT(&its->its_virtual);
1697         LIST_INIT(&its->its_prof);
1698         TAILQ_INIT(&its->its_worklist);
1699         for (i = 0; i < TIMER_MAX; i++)
1700                 its->its_timers[i] = NULL;
1701         PROC_LOCK(p);
1702         if (p->p_itimers == NULL) {
1703                 p->p_itimers = its;
1704                 PROC_UNLOCK(p);
1705         }
1706         else {
1707                 PROC_UNLOCK(p);
1708                 free(its, M_SUBPROC);
1709         }
1710 }
1711
1712 /* Clean up timers when some process events are being triggered. */
1713 static void
1714 itimers_event_exit_exec(int start_idx, struct proc *p)
1715 {
1716         struct itimers *its;
1717         struct itimer *it;
1718         int i;
1719
1720         its = p->p_itimers;
1721         if (its == NULL)
1722                 return;
1723
1724         for (i = start_idx; i < TIMER_MAX; ++i) {
1725                 if ((it = its->its_timers[i]) != NULL)
1726                         kern_ktimer_delete(curthread, i);
1727         }
1728         if (its->its_timers[0] == NULL && its->its_timers[1] == NULL &&
1729             its->its_timers[2] == NULL) {
1730                 free(its, M_SUBPROC);
1731                 p->p_itimers = NULL;
1732         }
1733 }
1734
1735 void
1736 itimers_exec(struct proc *p)
1737 {
1738         /*
1739          * According to susv3, XSI interval timers should be inherited
1740          * by new image.
1741          */
1742         itimers_event_exit_exec(3, p);
1743 }
1744
1745 void
1746 itimers_exit(struct proc *p)
1747 {
1748         itimers_event_exit_exec(0, p);
1749 }