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