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