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