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