]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - sys/kern/kern_time.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.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 <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/limits.h>
38 #include <sys/clock.h>
39 #include <sys/lock.h>
40 #include <sys/mutex.h>
41 #include <sys/sysproto.h>
42 #include <sys/eventhandler.h>
43 #include <sys/resourcevar.h>
44 #include <sys/signalvar.h>
45 #include <sys/kernel.h>
46 #include <sys/syscallsubr.h>
47 #include <sys/sysctl.h>
48 #include <sys/sysent.h>
49 #include <sys/priv.h>
50 #include <sys/proc.h>
51 #include <sys/posix4.h>
52 #include <sys/time.h>
53 #include <sys/timers.h>
54 #include <sys/timetc.h>
55 #include <sys/vnode.h>
56
57 #include <vm/vm.h>
58 #include <vm/vm_extern.h>
59
60 #define MAX_CLOCKS      (CLOCK_MONOTONIC+1)
61
62 static struct kclock    posix_clocks[MAX_CLOCKS];
63 static uma_zone_t       itimer_zone = NULL;
64
65 /*
66  * Time of day and interval timer support.
67  *
68  * These routines provide the kernel entry points to get and set
69  * the time-of-day and per-process interval timers.  Subroutines
70  * here provide support for adding and subtracting timeval structures
71  * and decrementing interval timers, optionally reloading the interval
72  * timers when they expire.
73  */
74
75 static int      settime(struct thread *, struct timeval *);
76 static void     timevalfix(struct timeval *);
77 static void     no_lease_updatetime(int);
78
79 static void     itimer_start(void);
80 static int      itimer_init(void *, int, int);
81 static void     itimer_fini(void *, int);
82 static void     itimer_enter(struct itimer *);
83 static void     itimer_leave(struct itimer *);
84 static struct itimer *itimer_find(struct proc *, int);
85 static void     itimers_alloc(struct proc *);
86 static void     itimers_event_hook_exec(void *arg, struct proc *p, struct image_params *imgp);
87 static void     itimers_event_hook_exit(void *arg, struct proc *p);
88 static int      realtimer_create(struct itimer *);
89 static int      realtimer_gettime(struct itimer *, struct itimerspec *);
90 static int      realtimer_settime(struct itimer *, int,
91                         struct itimerspec *, struct itimerspec *);
92 static int      realtimer_delete(struct itimer *);
93 static void     realtimer_clocktime(clockid_t, struct timespec *);
94 static void     realtimer_expire(void *);
95 static int      kern_timer_create(struct thread *, clockid_t,
96                         struct sigevent *, int *, int);
97 static int      kern_timer_delete(struct thread *, int);
98
99 int             register_posix_clock(int, struct kclock *);
100 void            itimer_fire(struct itimer *it);
101 int             itimespecfix(struct timespec *ts);
102
103 #define CLOCK_CALL(clock, call, arglist)                \
104         ((*posix_clocks[clock].call) arglist)
105
106 SYSINIT(posix_timer, SI_SUB_P1003_1B, SI_ORDER_FIRST+4, itimer_start, NULL);
107
108
109 static void 
110 no_lease_updatetime(deltat)
111         int deltat;
112 {
113 }
114
115 void (*lease_updatetime)(int)  = no_lease_updatetime;
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         (void) splsoftclock();
172         lease_updatetime(delta.tv_sec);
173         splx(s);
174         resettodr();
175         mtx_unlock(&Giant);
176         return (0);
177 }
178
179 #ifndef _SYS_SYSPROTO_H_
180 struct clock_gettime_args {
181         clockid_t clock_id;
182         struct  timespec *tp;
183 };
184 #endif
185 /* ARGSUSED */
186 int
187 clock_gettime(struct thread *td, struct clock_gettime_args *uap)
188 {
189         struct timespec ats;
190         int error;
191
192         error = kern_clock_gettime(td, uap->clock_id, &ats);
193         if (error == 0)
194                 error = copyout(&ats, uap->tp, sizeof(ats));
195
196         return (error);
197 }
198
199 int
200 kern_clock_gettime(struct thread *td, clockid_t clock_id, struct timespec *ats)
201 {
202         struct timeval sys, user;
203         struct proc *p;
204         uint64_t runtime, curtime, switchtime;
205
206         p = td->td_proc;
207         switch (clock_id) {
208         case CLOCK_REALTIME:            /* Default to precise. */
209         case CLOCK_REALTIME_PRECISE:
210                 nanotime(ats);
211                 break;
212         case CLOCK_REALTIME_FAST:
213                 getnanotime(ats);
214                 break;
215         case CLOCK_VIRTUAL:
216                 PROC_LOCK(p);
217                 PROC_SLOCK(p);
218                 calcru(p, &user, &sys);
219                 PROC_SUNLOCK(p);
220                 PROC_UNLOCK(p);
221                 TIMEVAL_TO_TIMESPEC(&user, ats);
222                 break;
223         case CLOCK_PROF:
224                 PROC_LOCK(p);
225                 PROC_SLOCK(p);
226                 calcru(p, &user, &sys);
227                 PROC_SUNLOCK(p);
228                 PROC_UNLOCK(p);
229                 timevaladd(&user, &sys);
230                 TIMEVAL_TO_TIMESPEC(&user, ats);
231                 break;
232         case CLOCK_MONOTONIC:           /* Default to precise. */
233         case CLOCK_MONOTONIC_PRECISE:
234         case CLOCK_UPTIME:
235         case CLOCK_UPTIME_PRECISE:
236                 nanouptime(ats);
237                 break;
238         case CLOCK_UPTIME_FAST:
239         case CLOCK_MONOTONIC_FAST:
240                 getnanouptime(ats);
241                 break;
242         case CLOCK_SECOND:
243                 ats->tv_sec = time_second;
244                 ats->tv_nsec = 0;
245                 break;
246         case CLOCK_THREAD_CPUTIME_ID:
247                 critical_enter();
248                 switchtime = PCPU_GET(switchtime);
249                 curtime = cpu_ticks();
250                 runtime = td->td_runtime;
251                 critical_exit();
252                 runtime = cputick2usec(runtime + curtime - switchtime);
253                 ats->tv_sec = runtime / 1000000;
254                 ats->tv_nsec = runtime % 1000000 * 1000;
255                 break;
256         default:
257                 return (EINVAL);
258         }
259         return (0);
260 }
261
262 #ifndef _SYS_SYSPROTO_H_
263 struct clock_settime_args {
264         clockid_t clock_id;
265         const struct    timespec *tp;
266 };
267 #endif
268 /* ARGSUSED */
269 int
270 clock_settime(struct thread *td, struct clock_settime_args *uap)
271 {
272         struct timespec ats;
273         int error;
274
275         if ((error = copyin(uap->tp, &ats, sizeof(ats))) != 0)
276                 return (error);
277         return (kern_clock_settime(td, uap->clock_id, &ats));
278 }
279
280 int
281 kern_clock_settime(struct thread *td, clockid_t clock_id, struct timespec *ats)
282 {
283         struct timeval atv;
284         int error;
285
286         if ((error = priv_check(td, PRIV_CLOCK_SETTIME)) != 0)
287                 return (error);
288         if (clock_id != CLOCK_REALTIME)
289                 return (EINVAL);
290         if (ats->tv_nsec < 0 || ats->tv_nsec >= 1000000000)
291                 return (EINVAL);
292         /* XXX Don't convert nsec->usec and back */
293         TIMESPEC_TO_TIMEVAL(&atv, ats);
294         error = settime(td, &atv);
295         return (error);
296 }
297
298 #ifndef _SYS_SYSPROTO_H_
299 struct clock_getres_args {
300         clockid_t clock_id;
301         struct  timespec *tp;
302 };
303 #endif
304 int
305 clock_getres(struct thread *td, struct clock_getres_args *uap)
306 {
307         struct timespec ts;
308         int error;
309
310         if (uap->tp == NULL)
311                 return (0);
312
313         error = kern_clock_getres(td, uap->clock_id, &ts);
314         if (error == 0)
315                 error = copyout(&ts, uap->tp, sizeof(ts));
316         return (error);
317 }
318
319 int
320 kern_clock_getres(struct thread *td, clockid_t clock_id, struct timespec *ts)
321 {
322
323         ts->tv_sec = 0;
324         switch (clock_id) {
325         case CLOCK_REALTIME:
326         case CLOCK_REALTIME_FAST:
327         case CLOCK_REALTIME_PRECISE:
328         case CLOCK_MONOTONIC:
329         case CLOCK_MONOTONIC_FAST:
330         case CLOCK_MONOTONIC_PRECISE:
331         case CLOCK_UPTIME:
332         case CLOCK_UPTIME_FAST:
333         case CLOCK_UPTIME_PRECISE:
334                 /*
335                  * Round up the result of the division cheaply by adding 1.
336                  * Rounding up is especially important if rounding down
337                  * would give 0.  Perfect rounding is unimportant.
338                  */
339                 ts->tv_nsec = 1000000000 / tc_getfrequency() + 1;
340                 break;
341         case CLOCK_VIRTUAL:
342         case CLOCK_PROF:
343                 /* Accurately round up here because we can do so cheaply. */
344                 ts->tv_nsec = (1000000000 + hz - 1) / hz;
345                 break;
346         case CLOCK_SECOND:
347                 ts->tv_sec = 1;
348                 ts->tv_nsec = 0;
349                 break;
350         default:
351                 return (EINVAL);
352         }
353         return (0);
354 }
355
356 static int nanowait;
357
358 int
359 kern_nanosleep(struct thread *td, struct timespec *rqt, struct timespec *rmt)
360 {
361         struct timespec ts, ts2, ts3;
362         struct timeval tv;
363         int error;
364
365         if (rqt->tv_nsec < 0 || rqt->tv_nsec >= 1000000000)
366                 return (EINVAL);
367         if (rqt->tv_sec < 0 || (rqt->tv_sec == 0 && rqt->tv_nsec == 0))
368                 return (0);
369         getnanouptime(&ts);
370         timespecadd(&ts, rqt);
371         TIMESPEC_TO_TIMEVAL(&tv, rqt);
372         for (;;) {
373                 error = tsleep(&nanowait, PWAIT | PCATCH, "nanslp",
374                     tvtohz(&tv));
375                 getnanouptime(&ts2);
376                 if (error != EWOULDBLOCK) {
377                         if (error == ERESTART)
378                                 error = EINTR;
379                         if (rmt != NULL) {
380                                 timespecsub(&ts, &ts2);
381                                 if (ts.tv_sec < 0)
382                                         timespecclear(&ts);
383                                 *rmt = ts;
384                         }
385                         return (error);
386                 }
387                 if (timespeccmp(&ts2, &ts, >=))
388                         return (0);
389                 ts3 = ts;
390                 timespecsub(&ts3, &ts2);
391                 TIMESPEC_TO_TIMEVAL(&tv, &ts3);
392         }
393 }
394
395 #ifndef _SYS_SYSPROTO_H_
396 struct nanosleep_args {
397         struct  timespec *rqtp;
398         struct  timespec *rmtp;
399 };
400 #endif
401 /* ARGSUSED */
402 int
403 nanosleep(struct thread *td, struct nanosleep_args *uap)
404 {
405         struct timespec rmt, rqt;
406         int error;
407
408         error = copyin(uap->rqtp, &rqt, sizeof(rqt));
409         if (error)
410                 return (error);
411
412         if (uap->rmtp &&
413             !useracc((caddr_t)uap->rmtp, sizeof(rmt), VM_PROT_WRITE))
414                         return (EFAULT);
415         error = kern_nanosleep(td, &rqt, &rmt);
416         if (error && uap->rmtp) {
417                 int error2;
418
419                 error2 = copyout(&rmt, uap->rmtp, sizeof(rmt));
420                 if (error2)
421                         error = error2;
422         }
423         return (error);
424 }
425
426 #ifndef _SYS_SYSPROTO_H_
427 struct gettimeofday_args {
428         struct  timeval *tp;
429         struct  timezone *tzp;
430 };
431 #endif
432 /* ARGSUSED */
433 int
434 gettimeofday(struct thread *td, struct gettimeofday_args *uap)
435 {
436         struct timeval atv;
437         struct timezone rtz;
438         int error = 0;
439
440         if (uap->tp) {
441                 microtime(&atv);
442                 error = copyout(&atv, uap->tp, sizeof (atv));
443         }
444         if (error == 0 && uap->tzp != NULL) {
445                 rtz.tz_minuteswest = tz_minuteswest;
446                 rtz.tz_dsttime = tz_dsttime;
447                 error = copyout(&rtz, uap->tzp, sizeof (rtz));
448         }
449         return (error);
450 }
451
452 #ifndef _SYS_SYSPROTO_H_
453 struct settimeofday_args {
454         struct  timeval *tv;
455         struct  timezone *tzp;
456 };
457 #endif
458 /* ARGSUSED */
459 int
460 settimeofday(struct thread *td, struct settimeofday_args *uap)
461 {
462         struct timeval atv, *tvp;
463         struct timezone atz, *tzp;
464         int error;
465
466         if (uap->tv) {
467                 error = copyin(uap->tv, &atv, sizeof(atv));
468                 if (error)
469                         return (error);
470                 tvp = &atv;
471         } else
472                 tvp = NULL;
473         if (uap->tzp) {
474                 error = copyin(uap->tzp, &atz, sizeof(atz));
475                 if (error)
476                         return (error);
477                 tzp = &atz;
478         } else
479                 tzp = NULL;
480         return (kern_settimeofday(td, tvp, tzp));
481 }
482
483 int
484 kern_settimeofday(struct thread *td, struct timeval *tv, struct timezone *tzp)
485 {
486         int error;
487
488         error = priv_check(td, PRIV_SETTIMEOFDAY);
489         if (error)
490                 return (error);
491         /* Verify all parameters before changing time. */
492         if (tv) {
493                 if (tv->tv_usec < 0 || tv->tv_usec >= 1000000)
494                         return (EINVAL);
495                 error = settime(td, tv);
496         }
497         if (tzp && error == 0) {
498                 tz_minuteswest = tzp->tz_minuteswest;
499                 tz_dsttime = tzp->tz_dsttime;
500         }
501         return (error);
502 }
503
504 /*
505  * Get value of an interval timer.  The process virtual and profiling virtual
506  * time timers are kept in the p_stats area, since they can be swapped out.
507  * These are kept internally in the way they are specified externally: in
508  * time until they expire.
509  *
510  * The real time interval timer is kept in the process table slot for the
511  * process, and its value (it_value) is kept as an absolute time rather than
512  * as a delta, so that it is easy to keep periodic real-time signals from
513  * drifting.
514  *
515  * Virtual time timers are processed in the hardclock() routine of
516  * kern_clock.c.  The real time timer is processed by a timeout routine,
517  * called from the softclock() routine.  Since a callout may be delayed in
518  * real time due to interrupt processing in the system, it is possible for
519  * the real time timeout routine (realitexpire, given below), to be delayed
520  * in real time past when it is supposed to occur.  It does not suffice,
521  * therefore, to reload the real timer .it_value from the real time timers
522  * .it_interval.  Rather, we compute the next time in absolute time the timer
523  * should go off.
524  */
525 #ifndef _SYS_SYSPROTO_H_
526 struct getitimer_args {
527         u_int   which;
528         struct  itimerval *itv;
529 };
530 #endif
531 int
532 getitimer(struct thread *td, struct getitimer_args *uap)
533 {
534         struct itimerval aitv;
535         int error;
536
537         error = kern_getitimer(td, uap->which, &aitv);
538         if (error != 0)
539                 return (error);
540         return (copyout(&aitv, uap->itv, sizeof (struct itimerval)));
541 }
542
543 int
544 kern_getitimer(struct thread *td, u_int which, struct itimerval *aitv)
545 {
546         struct proc *p = td->td_proc;
547         struct timeval ctv;
548
549         if (which > ITIMER_PROF)
550                 return (EINVAL);
551
552         if (which == ITIMER_REAL) {
553                 /*
554                  * Convert from absolute to relative time in .it_value
555                  * part of real time timer.  If time for real time timer
556                  * has passed return 0, else return difference between
557                  * current time and time for the timer to go off.
558                  */
559                 PROC_LOCK(p);
560                 *aitv = p->p_realtimer;
561                 PROC_UNLOCK(p);
562                 if (timevalisset(&aitv->it_value)) {
563                         getmicrouptime(&ctv);
564                         if (timevalcmp(&aitv->it_value, &ctv, <))
565                                 timevalclear(&aitv->it_value);
566                         else
567                                 timevalsub(&aitv->it_value, &ctv);
568                 }
569         } else {
570                 PROC_SLOCK(p);
571                 *aitv = p->p_stats->p_timer[which];
572                 PROC_SUNLOCK(p);
573         }
574         return (0);
575 }
576
577 #ifndef _SYS_SYSPROTO_H_
578 struct setitimer_args {
579         u_int   which;
580         struct  itimerval *itv, *oitv;
581 };
582 #endif
583 int
584 setitimer(struct thread *td, struct setitimer_args *uap)
585 {
586         struct itimerval aitv, oitv;
587         int error;
588
589         if (uap->itv == NULL) {
590                 uap->itv = uap->oitv;
591                 return (getitimer(td, (struct getitimer_args *)uap));
592         }
593
594         if ((error = copyin(uap->itv, &aitv, sizeof(struct itimerval))))
595                 return (error);
596         error = kern_setitimer(td, uap->which, &aitv, &oitv);
597         if (error != 0 || uap->oitv == NULL)
598                 return (error);
599         return (copyout(&oitv, uap->oitv, sizeof(struct itimerval)));
600 }
601
602 int
603 kern_setitimer(struct thread *td, u_int which, struct itimerval *aitv,
604     struct itimerval *oitv)
605 {
606         struct proc *p = td->td_proc;
607         struct timeval ctv;
608
609         if (aitv == NULL)
610                 return (kern_getitimer(td, which, oitv));
611
612         if (which > ITIMER_PROF)
613                 return (EINVAL);
614         if (itimerfix(&aitv->it_value))
615                 return (EINVAL);
616         if (!timevalisset(&aitv->it_value))
617                 timevalclear(&aitv->it_interval);
618         else if (itimerfix(&aitv->it_interval))
619                 return (EINVAL);
620
621         if (which == ITIMER_REAL) {
622                 PROC_LOCK(p);
623                 if (timevalisset(&p->p_realtimer.it_value))
624                         callout_stop(&p->p_itcallout);
625                 getmicrouptime(&ctv);
626                 if (timevalisset(&aitv->it_value)) {
627                         callout_reset(&p->p_itcallout, tvtohz(&aitv->it_value),
628                             realitexpire, p);
629                         timevaladd(&aitv->it_value, &ctv);
630                 }
631                 *oitv = p->p_realtimer;
632                 p->p_realtimer = *aitv;
633                 PROC_UNLOCK(p);
634                 if (timevalisset(&oitv->it_value)) {
635                         if (timevalcmp(&oitv->it_value, &ctv, <))
636                                 timevalclear(&oitv->it_value);
637                         else
638                                 timevalsub(&oitv->it_value, &ctv);
639                 }
640         } else {
641                 PROC_SLOCK(p);
642                 *oitv = p->p_stats->p_timer[which];
643                 p->p_stats->p_timer[which] = *aitv;
644                 PROC_SUNLOCK(p);
645         }
646         return (0);
647 }
648
649 /*
650  * Real interval timer expired:
651  * send process whose timer expired an alarm signal.
652  * If time is not set up to reload, then just return.
653  * Else compute next time timer should go off which is > current time.
654  * This is where delay in processing this timeout causes multiple
655  * SIGALRM calls to be compressed into one.
656  * tvtohz() always adds 1 to allow for the time until the next clock
657  * interrupt being strictly less than 1 clock tick, but we don't want
658  * that here since we want to appear to be in sync with the clock
659  * interrupt even when we're delayed.
660  */
661 void
662 realitexpire(void *arg)
663 {
664         struct proc *p;
665         struct timeval ctv, ntv;
666
667         p = (struct proc *)arg;
668         PROC_LOCK(p);
669         psignal(p, SIGALRM);
670         if (!timevalisset(&p->p_realtimer.it_interval)) {
671                 timevalclear(&p->p_realtimer.it_value);
672                 if (p->p_flag & P_WEXIT)
673                         wakeup(&p->p_itcallout);
674                 PROC_UNLOCK(p);
675                 return;
676         }
677         for (;;) {
678                 timevaladd(&p->p_realtimer.it_value,
679                     &p->p_realtimer.it_interval);
680                 getmicrouptime(&ctv);
681                 if (timevalcmp(&p->p_realtimer.it_value, &ctv, >)) {
682                         ntv = p->p_realtimer.it_value;
683                         timevalsub(&ntv, &ctv);
684                         callout_reset(&p->p_itcallout, tvtohz(&ntv) - 1,
685                             realitexpire, p);
686                         PROC_UNLOCK(p);
687                         return;
688                 }
689         }
690         /*NOTREACHED*/
691 }
692
693 /*
694  * Check that a proposed value to load into the .it_value or
695  * .it_interval part of an interval timer is acceptable, and
696  * fix it to have at least minimal value (i.e. if it is less
697  * than the resolution of the clock, round it up.)
698  */
699 int
700 itimerfix(struct timeval *tv)
701 {
702
703         if (tv->tv_sec < 0 || tv->tv_usec < 0 || tv->tv_usec >= 1000000)
704                 return (EINVAL);
705         if (tv->tv_sec == 0 && tv->tv_usec != 0 && tv->tv_usec < tick)
706                 tv->tv_usec = tick;
707         return (0);
708 }
709
710 /*
711  * Decrement an interval timer by a specified number
712  * of microseconds, which must be less than a second,
713  * i.e. < 1000000.  If the timer expires, then reload
714  * it.  In this case, carry over (usec - old value) to
715  * reduce the value reloaded into the timer so that
716  * the timer does not drift.  This routine assumes
717  * that it is called in a context where the timers
718  * on which it is operating cannot change in value.
719  */
720 int
721 itimerdecr(struct itimerval *itp, int usec)
722 {
723
724         if (itp->it_value.tv_usec < usec) {
725                 if (itp->it_value.tv_sec == 0) {
726                         /* expired, and already in next interval */
727                         usec -= itp->it_value.tv_usec;
728                         goto expire;
729                 }
730                 itp->it_value.tv_usec += 1000000;
731                 itp->it_value.tv_sec--;
732         }
733         itp->it_value.tv_usec -= usec;
734         usec = 0;
735         if (timevalisset(&itp->it_value))
736                 return (1);
737         /* expired, exactly at end of interval */
738 expire:
739         if (timevalisset(&itp->it_interval)) {
740                 itp->it_value = itp->it_interval;
741                 itp->it_value.tv_usec -= usec;
742                 if (itp->it_value.tv_usec < 0) {
743                         itp->it_value.tv_usec += 1000000;
744                         itp->it_value.tv_sec--;
745                 }
746         } else
747                 itp->it_value.tv_usec = 0;              /* sec is already 0 */
748         return (0);
749 }
750
751 /*
752  * Add and subtract routines for timevals.
753  * N.B.: subtract routine doesn't deal with
754  * results which are before the beginning,
755  * it just gets very confused in this case.
756  * Caveat emptor.
757  */
758 void
759 timevaladd(struct timeval *t1, const struct timeval *t2)
760 {
761
762         t1->tv_sec += t2->tv_sec;
763         t1->tv_usec += t2->tv_usec;
764         timevalfix(t1);
765 }
766
767 void
768 timevalsub(struct timeval *t1, const struct timeval *t2)
769 {
770
771         t1->tv_sec -= t2->tv_sec;
772         t1->tv_usec -= t2->tv_usec;
773         timevalfix(t1);
774 }
775
776 static void
777 timevalfix(struct timeval *t1)
778 {
779
780         if (t1->tv_usec < 0) {
781                 t1->tv_sec--;
782                 t1->tv_usec += 1000000;
783         }
784         if (t1->tv_usec >= 1000000) {
785                 t1->tv_sec++;
786                 t1->tv_usec -= 1000000;
787         }
788 }
789
790 /*
791  * ratecheck(): simple time-based rate-limit checking.
792  */
793 int
794 ratecheck(struct timeval *lasttime, const struct timeval *mininterval)
795 {
796         struct timeval tv, delta;
797         int rv = 0;
798
799         getmicrouptime(&tv);            /* NB: 10ms precision */
800         delta = tv;
801         timevalsub(&delta, lasttime);
802
803         /*
804          * check for 0,0 is so that the message will be seen at least once,
805          * even if interval is huge.
806          */
807         if (timevalcmp(&delta, mininterval, >=) ||
808             (lasttime->tv_sec == 0 && lasttime->tv_usec == 0)) {
809                 *lasttime = tv;
810                 rv = 1;
811         }
812
813         return (rv);
814 }
815
816 /*
817  * ppsratecheck(): packets (or events) per second limitation.
818  *
819  * Return 0 if the limit is to be enforced (e.g. the caller
820  * should drop a packet because of the rate limitation).
821  *
822  * maxpps of 0 always causes zero to be returned.  maxpps of -1
823  * always causes 1 to be returned; this effectively defeats rate
824  * limiting.
825  *
826  * Note that we maintain the struct timeval for compatibility
827  * with other bsd systems.  We reuse the storage and just monitor
828  * clock ticks for minimal overhead.  
829  */
830 int
831 ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
832 {
833         int now;
834
835         /*
836          * Reset the last time and counter if this is the first call
837          * or more than a second has passed since the last update of
838          * lasttime.
839          */
840         now = ticks;
841         if (lasttime->tv_sec == 0 || (u_int)(now - lasttime->tv_sec) >= hz) {
842                 lasttime->tv_sec = now;
843                 *curpps = 1;
844                 return (maxpps != 0);
845         } else {
846                 (*curpps)++;            /* NB: ignore potential overflow */
847                 return (maxpps < 0 || *curpps < maxpps);
848         }
849 }
850
851 static void
852 itimer_start(void)
853 {
854         struct kclock rt_clock = {
855                 .timer_create  = realtimer_create,
856                 .timer_delete  = realtimer_delete,
857                 .timer_settime = realtimer_settime,
858                 .timer_gettime = realtimer_gettime,
859                 .event_hook    = NULL
860         };
861
862         itimer_zone = uma_zcreate("itimer", sizeof(struct itimer),
863                 NULL, NULL, itimer_init, itimer_fini, UMA_ALIGN_PTR, 0);
864         register_posix_clock(CLOCK_REALTIME,  &rt_clock);
865         register_posix_clock(CLOCK_MONOTONIC, &rt_clock);
866         p31b_setcfg(CTL_P1003_1B_TIMERS, 200112L);
867         p31b_setcfg(CTL_P1003_1B_DELAYTIMER_MAX, INT_MAX);
868         p31b_setcfg(CTL_P1003_1B_TIMER_MAX, TIMER_MAX);
869         EVENTHANDLER_REGISTER(process_exit, itimers_event_hook_exit,
870                 (void *)ITIMER_EV_EXIT, EVENTHANDLER_PRI_ANY);
871         EVENTHANDLER_REGISTER(process_exec, itimers_event_hook_exec,
872                 (void *)ITIMER_EV_EXEC, EVENTHANDLER_PRI_ANY);
873 }
874
875 int
876 register_posix_clock(int clockid, struct kclock *clk)
877 {
878         if ((unsigned)clockid >= MAX_CLOCKS) {
879                 printf("%s: invalid clockid\n", __func__);
880                 return (0);
881         }
882         posix_clocks[clockid] = *clk;
883         return (1);
884 }
885
886 static int
887 itimer_init(void *mem, int size, int flags)
888 {
889         struct itimer *it;
890
891         it = (struct itimer *)mem;
892         mtx_init(&it->it_mtx, "itimer lock", NULL, MTX_DEF);
893         return (0);
894 }
895
896 static void
897 itimer_fini(void *mem, int size)
898 {
899         struct itimer *it;
900
901         it = (struct itimer *)mem;
902         mtx_destroy(&it->it_mtx);
903 }
904
905 static void
906 itimer_enter(struct itimer *it)
907 {
908
909         mtx_assert(&it->it_mtx, MA_OWNED);
910         it->it_usecount++;
911 }
912
913 static void
914 itimer_leave(struct itimer *it)
915 {
916
917         mtx_assert(&it->it_mtx, MA_OWNED);
918         KASSERT(it->it_usecount > 0, ("invalid it_usecount"));
919
920         if (--it->it_usecount == 0 && (it->it_flags & ITF_WANTED) != 0)
921                 wakeup(it);
922 }
923
924 #ifndef _SYS_SYSPROTO_H_
925 struct ktimer_create_args {
926         clockid_t clock_id;
927         struct sigevent * evp;
928         int * timerid;
929 };
930 #endif
931 int
932 ktimer_create(struct thread *td, struct ktimer_create_args *uap)
933 {
934         struct sigevent *evp1, ev;
935         int id;
936         int error;
937
938         if (uap->evp != NULL) {
939                 error = copyin(uap->evp, &ev, sizeof(ev));
940                 if (error != 0)
941                         return (error);
942                 evp1 = &ev;
943         } else
944                 evp1 = NULL;
945
946         error = kern_timer_create(td, uap->clock_id, evp1, &id, -1);
947
948         if (error == 0) {
949                 error = copyout(&id, uap->timerid, sizeof(int));
950                 if (error != 0)
951                         kern_timer_delete(td, id);
952         }
953         return (error);
954 }
955
956 static int
957 kern_timer_create(struct thread *td, clockid_t clock_id,
958         struct sigevent *evp, int *timerid, int preset_id)
959 {
960         struct proc *p = td->td_proc;
961         struct itimer *it;
962         int id;
963         int error;
964
965         if (clock_id < 0 || clock_id >= MAX_CLOCKS)
966                 return (EINVAL);
967
968         if (posix_clocks[clock_id].timer_create == NULL)
969                 return (EINVAL);
970
971         if (evp != NULL) {
972                 if (evp->sigev_notify != SIGEV_NONE &&
973                     evp->sigev_notify != SIGEV_SIGNAL &&
974                     evp->sigev_notify != SIGEV_THREAD_ID)
975                         return (EINVAL);
976                 if ((evp->sigev_notify == SIGEV_SIGNAL ||
977                      evp->sigev_notify == SIGEV_THREAD_ID) &&
978                         !_SIG_VALID(evp->sigev_signo))
979                         return (EINVAL);
980         }
981         
982         if (p->p_itimers == NULL)
983                 itimers_alloc(p);
984         
985         it = uma_zalloc(itimer_zone, M_WAITOK);
986         it->it_flags = 0;
987         it->it_usecount = 0;
988         it->it_active = 0;
989         timespecclear(&it->it_time.it_value);
990         timespecclear(&it->it_time.it_interval);
991         it->it_overrun = 0;
992         it->it_overrun_last = 0;
993         it->it_clockid = clock_id;
994         it->it_timerid = -1;
995         it->it_proc = p;
996         ksiginfo_init(&it->it_ksi);
997         it->it_ksi.ksi_flags |= KSI_INS | KSI_EXT;
998         error = CLOCK_CALL(clock_id, timer_create, (it));
999         if (error != 0)
1000                 goto out;
1001
1002         PROC_LOCK(p);
1003         if (preset_id != -1) {
1004                 KASSERT(preset_id >= 0 && preset_id < 3, ("invalid preset_id"));
1005                 id = preset_id;
1006                 if (p->p_itimers->its_timers[id] != NULL) {
1007                         PROC_UNLOCK(p);
1008                         error = 0;
1009                         goto out;
1010                 }
1011         } else {
1012                 /*
1013                  * Find a free timer slot, skipping those reserved
1014                  * for setitimer().
1015                  */
1016                 for (id = 3; id < TIMER_MAX; id++)
1017                         if (p->p_itimers->its_timers[id] == NULL)
1018                                 break;
1019                 if (id == TIMER_MAX) {
1020                         PROC_UNLOCK(p);
1021                         error = EAGAIN;
1022                         goto out;
1023                 }
1024         }
1025         it->it_timerid = id;
1026         p->p_itimers->its_timers[id] = it;
1027         if (evp != NULL)
1028                 it->it_sigev = *evp;
1029         else {
1030                 it->it_sigev.sigev_notify = SIGEV_SIGNAL;
1031                 switch (clock_id) {
1032                 default:
1033                 case CLOCK_REALTIME:
1034                         it->it_sigev.sigev_signo = SIGALRM;
1035                         break;
1036                 case CLOCK_VIRTUAL:
1037                         it->it_sigev.sigev_signo = SIGVTALRM;
1038                         break;
1039                 case CLOCK_PROF:
1040                         it->it_sigev.sigev_signo = SIGPROF;
1041                         break;
1042                 }
1043                 it->it_sigev.sigev_value.sival_int = id;
1044         }
1045
1046         if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1047             it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1048                 it->it_ksi.ksi_signo = it->it_sigev.sigev_signo;
1049                 it->it_ksi.ksi_code = SI_TIMER;
1050                 it->it_ksi.ksi_value = it->it_sigev.sigev_value;
1051                 it->it_ksi.ksi_timerid = id;
1052         }
1053         PROC_UNLOCK(p);
1054         *timerid = id;
1055         return (0);
1056
1057 out:
1058         ITIMER_LOCK(it);
1059         CLOCK_CALL(it->it_clockid, timer_delete, (it));
1060         ITIMER_UNLOCK(it);
1061         uma_zfree(itimer_zone, it);
1062         return (error);
1063 }
1064
1065 #ifndef _SYS_SYSPROTO_H_
1066 struct ktimer_delete_args {
1067         int timerid;
1068 };
1069 #endif
1070 int
1071 ktimer_delete(struct thread *td, struct ktimer_delete_args *uap)
1072 {
1073         return (kern_timer_delete(td, uap->timerid));
1074 }
1075
1076 static struct itimer *
1077 itimer_find(struct proc *p, int timerid)
1078 {
1079         struct itimer *it;
1080
1081         PROC_LOCK_ASSERT(p, MA_OWNED);
1082         if ((p->p_itimers == NULL) ||
1083             (timerid < 0) || (timerid >= TIMER_MAX) ||
1084             (it = p->p_itimers->its_timers[timerid]) == NULL) {
1085                 return (NULL);
1086         }
1087         ITIMER_LOCK(it);
1088         if ((it->it_flags & ITF_DELETING) != 0) {
1089                 ITIMER_UNLOCK(it);
1090                 it = NULL;
1091         }
1092         return (it);
1093 }
1094
1095 static int
1096 kern_timer_delete(struct thread *td, int timerid)
1097 {
1098         struct proc *p = td->td_proc;
1099         struct itimer *it;
1100
1101         PROC_LOCK(p);
1102         it = itimer_find(p, timerid);
1103         if (it == NULL) {
1104                 PROC_UNLOCK(p);
1105                 return (EINVAL);
1106         }
1107         PROC_UNLOCK(p);
1108
1109         it->it_flags |= ITF_DELETING;
1110         while (it->it_usecount > 0) {
1111                 it->it_flags |= ITF_WANTED;
1112                 msleep(it, &it->it_mtx, PPAUSE, "itimer", 0);
1113         }
1114         it->it_flags &= ~ITF_WANTED;
1115         CLOCK_CALL(it->it_clockid, timer_delete, (it));
1116         ITIMER_UNLOCK(it);
1117
1118         PROC_LOCK(p);
1119         if (KSI_ONQ(&it->it_ksi))
1120                 sigqueue_take(&it->it_ksi);
1121         p->p_itimers->its_timers[timerid] = NULL;
1122         PROC_UNLOCK(p);
1123         uma_zfree(itimer_zone, it);
1124         return (0);
1125 }
1126
1127 #ifndef _SYS_SYSPROTO_H_
1128 struct ktimer_settime_args {
1129         int timerid;
1130         int flags;
1131         const struct itimerspec * value;
1132         struct itimerspec * ovalue;
1133 };
1134 #endif
1135 int
1136 ktimer_settime(struct thread *td, struct ktimer_settime_args *uap)
1137 {
1138         struct proc *p = td->td_proc;
1139         struct itimer *it;
1140         struct itimerspec val, oval, *ovalp;
1141         int error;
1142
1143         error = copyin(uap->value, &val, sizeof(val));
1144         if (error != 0)
1145                 return (error);
1146         
1147         if (uap->ovalue != NULL)
1148                 ovalp = &oval;
1149         else
1150                 ovalp = NULL;
1151
1152         PROC_LOCK(p);
1153         if (uap->timerid < 3 ||
1154             (it = itimer_find(p, uap->timerid)) == NULL) {
1155                 PROC_UNLOCK(p);
1156                 error = EINVAL;
1157         } else {
1158                 PROC_UNLOCK(p);
1159                 itimer_enter(it);
1160                 error = CLOCK_CALL(it->it_clockid, timer_settime,
1161                                 (it, uap->flags, &val, ovalp));
1162                 itimer_leave(it);
1163                 ITIMER_UNLOCK(it);
1164         }
1165         if (error == 0 && uap->ovalue != NULL)
1166                 error = copyout(ovalp, uap->ovalue, sizeof(*ovalp));
1167         return (error);
1168 }
1169
1170 #ifndef _SYS_SYSPROTO_H_
1171 struct ktimer_gettime_args {
1172         int timerid;
1173         struct itimerspec * value;
1174 };
1175 #endif
1176 int
1177 ktimer_gettime(struct thread *td, struct ktimer_gettime_args *uap)
1178 {
1179         struct proc *p = td->td_proc;
1180         struct itimer *it;
1181         struct itimerspec val;
1182         int error;
1183
1184         PROC_LOCK(p);
1185         if (uap->timerid < 3 ||
1186            (it = itimer_find(p, uap->timerid)) == NULL) {
1187                 PROC_UNLOCK(p);
1188                 error = EINVAL;
1189         } else {
1190                 PROC_UNLOCK(p);
1191                 itimer_enter(it);
1192                 error = CLOCK_CALL(it->it_clockid, timer_gettime,
1193                                 (it, &val));
1194                 itimer_leave(it);
1195                 ITIMER_UNLOCK(it);
1196         }
1197         if (error == 0)
1198                 error = copyout(&val, uap->value, sizeof(val));
1199         return (error);
1200 }
1201
1202 #ifndef _SYS_SYSPROTO_H_
1203 struct timer_getoverrun_args {
1204         int timerid;
1205 };
1206 #endif
1207 int
1208 ktimer_getoverrun(struct thread *td, struct ktimer_getoverrun_args *uap)
1209 {
1210         struct proc *p = td->td_proc;
1211         struct itimer *it;
1212         int error ;
1213
1214         PROC_LOCK(p);
1215         if (uap->timerid < 3 ||
1216             (it = itimer_find(p, uap->timerid)) == NULL) {
1217                 PROC_UNLOCK(p);
1218                 error = EINVAL;
1219         } else {
1220                 td->td_retval[0] = it->it_overrun_last;
1221                 ITIMER_UNLOCK(it);
1222                 PROC_UNLOCK(p);
1223                 error = 0;
1224         }
1225         return (error);
1226 }
1227
1228 static int
1229 realtimer_create(struct itimer *it)
1230 {
1231         callout_init_mtx(&it->it_callout, &it->it_mtx, 0);
1232         return (0);
1233 }
1234
1235 static int
1236 realtimer_delete(struct itimer *it)
1237 {
1238         mtx_assert(&it->it_mtx, MA_OWNED);
1239         
1240         /*
1241          * clear timer's value and interval to tell realtimer_expire
1242          * to not rearm the timer.
1243          */
1244         timespecclear(&it->it_time.it_value);
1245         timespecclear(&it->it_time.it_interval);
1246         ITIMER_UNLOCK(it);
1247         callout_drain(&it->it_callout);
1248         ITIMER_LOCK(it);
1249         return (0);
1250 }
1251
1252 static int
1253 realtimer_gettime(struct itimer *it, struct itimerspec *ovalue)
1254 {
1255         struct timespec cts;
1256
1257         mtx_assert(&it->it_mtx, MA_OWNED);
1258
1259         realtimer_clocktime(it->it_clockid, &cts);
1260         *ovalue = it->it_time;
1261         if (ovalue->it_value.tv_sec != 0 || ovalue->it_value.tv_nsec != 0) {
1262                 timespecsub(&ovalue->it_value, &cts);
1263                 if (ovalue->it_value.tv_sec < 0 ||
1264                     (ovalue->it_value.tv_sec == 0 &&
1265                      ovalue->it_value.tv_nsec == 0)) {
1266                         ovalue->it_value.tv_sec  = 0;
1267                         ovalue->it_value.tv_nsec = 1;
1268                 }
1269         }
1270         return (0);
1271 }
1272
1273 static int
1274 realtimer_settime(struct itimer *it, int flags,
1275         struct itimerspec *value, struct itimerspec *ovalue)
1276 {
1277         struct timespec cts, ts;
1278         struct timeval tv;
1279         struct itimerspec val;
1280
1281         mtx_assert(&it->it_mtx, MA_OWNED);
1282
1283         val = *value;
1284         if (itimespecfix(&val.it_value))
1285                 return (EINVAL);
1286
1287         if (timespecisset(&val.it_value)) {
1288                 if (itimespecfix(&val.it_interval))
1289                         return (EINVAL);
1290         } else {
1291                 timespecclear(&val.it_interval);
1292         }
1293         
1294         if (ovalue != NULL)
1295                 realtimer_gettime(it, ovalue);
1296
1297         it->it_time = val;
1298         if (timespecisset(&val.it_value)) {
1299                 realtimer_clocktime(it->it_clockid, &cts);
1300                 ts = val.it_value;
1301                 if ((flags & TIMER_ABSTIME) == 0) {
1302                         /* Convert to absolute time. */
1303                         timespecadd(&it->it_time.it_value, &cts);
1304                 } else {
1305                         timespecsub(&ts, &cts);
1306                         /*
1307                          * We don't care if ts is negative, tztohz will
1308                          * fix it.
1309                          */
1310                 }
1311                 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1312                 callout_reset(&it->it_callout, tvtohz(&tv),
1313                         realtimer_expire, it);
1314         } else {
1315                 callout_stop(&it->it_callout);
1316         }
1317
1318         return (0);
1319 }
1320
1321 static void
1322 realtimer_clocktime(clockid_t id, struct timespec *ts)
1323 {
1324         if (id == CLOCK_REALTIME)
1325                 getnanotime(ts);
1326         else    /* CLOCK_MONOTONIC */
1327                 getnanouptime(ts);
1328 }
1329
1330 int
1331 itimer_accept(struct proc *p, int timerid, ksiginfo_t *ksi)
1332 {
1333         struct itimer *it;
1334
1335         PROC_LOCK_ASSERT(p, MA_OWNED);
1336         it = itimer_find(p, timerid);
1337         if (it != NULL) {
1338                 ksi->ksi_overrun = it->it_overrun;
1339                 it->it_overrun_last = it->it_overrun;
1340                 it->it_overrun = 0;
1341                 ITIMER_UNLOCK(it);
1342                 return (0);
1343         }
1344         return (EINVAL);
1345 }
1346
1347 int
1348 itimespecfix(struct timespec *ts)
1349 {
1350
1351         if (ts->tv_sec < 0 || ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000)
1352                 return (EINVAL);
1353         if (ts->tv_sec == 0 && ts->tv_nsec != 0 && ts->tv_nsec < tick * 1000)
1354                 ts->tv_nsec = tick * 1000;
1355         return (0);
1356 }
1357
1358 /* Timeout callback for realtime timer */
1359 static void
1360 realtimer_expire(void *arg)
1361 {
1362         struct timespec cts, ts;
1363         struct timeval tv;
1364         struct itimer *it;
1365         struct proc *p;
1366
1367         it = (struct itimer *)arg;
1368         p = it->it_proc;
1369
1370         realtimer_clocktime(it->it_clockid, &cts);
1371         /* Only fire if time is reached. */
1372         if (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1373                 if (timespecisset(&it->it_time.it_interval)) {
1374                         timespecadd(&it->it_time.it_value,
1375                                     &it->it_time.it_interval);
1376                         while (timespeccmp(&cts, &it->it_time.it_value, >=)) {
1377                                 if (it->it_overrun < INT_MAX)
1378                                         it->it_overrun++;
1379                                 else
1380                                         it->it_ksi.ksi_errno = ERANGE;
1381                                 timespecadd(&it->it_time.it_value,
1382                                             &it->it_time.it_interval);
1383                         }
1384                 } else {
1385                         /* single shot timer ? */
1386                         timespecclear(&it->it_time.it_value);
1387                 }
1388                 if (timespecisset(&it->it_time.it_value)) {
1389                         ts = it->it_time.it_value;
1390                         timespecsub(&ts, &cts);
1391                         TIMESPEC_TO_TIMEVAL(&tv, &ts);
1392                         callout_reset(&it->it_callout, tvtohz(&tv),
1393                                  realtimer_expire, it);
1394                 }
1395                 itimer_enter(it);
1396                 ITIMER_UNLOCK(it);
1397                 itimer_fire(it);
1398                 ITIMER_LOCK(it);
1399                 itimer_leave(it);
1400         } else if (timespecisset(&it->it_time.it_value)) {
1401                 ts = it->it_time.it_value;
1402                 timespecsub(&ts, &cts);
1403                 TIMESPEC_TO_TIMEVAL(&tv, &ts);
1404                 callout_reset(&it->it_callout, tvtohz(&tv), realtimer_expire,
1405                         it);
1406         }
1407 }
1408
1409 void
1410 itimer_fire(struct itimer *it)
1411 {
1412         struct proc *p = it->it_proc;
1413         int ret;
1414
1415         if (it->it_sigev.sigev_notify == SIGEV_SIGNAL ||
1416             it->it_sigev.sigev_notify == SIGEV_THREAD_ID) {
1417                 PROC_LOCK(p);
1418                 if (!KSI_ONQ(&it->it_ksi)) {
1419                         it->it_ksi.ksi_errno = 0;
1420                         ret = psignal_event(p, &it->it_sigev, &it->it_ksi);
1421                         if (__predict_false(ret != 0)) {
1422                                 it->it_overrun++;
1423                                 /*
1424                                  * Broken userland code, thread went
1425                                  * away, disarm the timer.
1426                                  */
1427                                 if (ret == ESRCH) {
1428                                         ITIMER_LOCK(it);
1429                                         timespecclear(&it->it_time.it_value);
1430                                         timespecclear(&it->it_time.it_interval);
1431                                         callout_stop(&it->it_callout);
1432                                         ITIMER_UNLOCK(it);
1433                                 }
1434                         }
1435                 } else {
1436                         if (it->it_overrun < INT_MAX)
1437                                 it->it_overrun++;
1438                         else
1439                                 it->it_ksi.ksi_errno = ERANGE;
1440                 }
1441                 PROC_UNLOCK(p);
1442         }
1443 }
1444
1445 static void
1446 itimers_alloc(struct proc *p)
1447 {
1448         struct itimers *its;
1449         int i;
1450
1451         its = malloc(sizeof (struct itimers), M_SUBPROC, M_WAITOK | M_ZERO);
1452         LIST_INIT(&its->its_virtual);
1453         LIST_INIT(&its->its_prof);
1454         TAILQ_INIT(&its->its_worklist);
1455         for (i = 0; i < TIMER_MAX; i++)
1456                 its->its_timers[i] = NULL;
1457         PROC_LOCK(p);
1458         if (p->p_itimers == NULL) {
1459                 p->p_itimers = its;
1460                 PROC_UNLOCK(p);
1461         }
1462         else {
1463                 PROC_UNLOCK(p);
1464                 free(its, M_SUBPROC);
1465         }
1466 }
1467
1468 static void
1469 itimers_event_hook_exec(void *arg, struct proc *p, struct image_params *imgp __unused)
1470 {
1471         itimers_event_hook_exit(arg, p);
1472 }
1473
1474 /* Clean up timers when some process events are being triggered. */
1475 static void
1476 itimers_event_hook_exit(void *arg, struct proc *p)
1477 {
1478         struct itimers *its;
1479         struct itimer *it;
1480         int event = (int)(intptr_t)arg;
1481         int i;
1482
1483         if (p->p_itimers != NULL) {
1484                 its = p->p_itimers;
1485                 for (i = 0; i < MAX_CLOCKS; ++i) {
1486                         if (posix_clocks[i].event_hook != NULL)
1487                                 CLOCK_CALL(i, event_hook, (p, i, event));
1488                 }
1489                 /*
1490                  * According to susv3, XSI interval timers should be inherited
1491                  * by new image.
1492                  */
1493                 if (event == ITIMER_EV_EXEC)
1494                         i = 3;
1495                 else if (event == ITIMER_EV_EXIT)
1496                         i = 0;
1497                 else
1498                         panic("unhandled event");
1499                 for (; i < TIMER_MAX; ++i) {
1500                         if ((it = its->its_timers[i]) != NULL)
1501                                 kern_timer_delete(curthread, i);
1502                 }
1503                 if (its->its_timers[0] == NULL &&
1504                     its->its_timers[1] == NULL &&
1505                     its->its_timers[2] == NULL) {
1506                         free(its, M_SUBPROC);
1507                         p->p_itimers = NULL;
1508                 }
1509         }
1510 }