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