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