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