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