/
kern_time.c
1794 lines (1589 loc) · 42.8 KB
/
kern_time.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* $NetBSD: kern_time.c,v 1.214 2022/05/15 16:20:10 riastradh Exp $ */
/*-
* Copyright (c) 2000, 2004, 2005, 2007, 2008, 2009, 2020
* The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Christopher G. Demetriou, by Andrew Doran, and by Jason R. Thorpe.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Copyright (c) 1982, 1986, 1989, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)kern_time.c 8.4 (Berkeley) 5/26/95
*/
#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: kern_time.c,v 1.214 2022/05/15 16:20:10 riastradh Exp $");
#include <sys/param.h>
#include <sys/resourcevar.h>
#include <sys/kernel.h>
#include <sys/systm.h>
#include <sys/proc.h>
#include <sys/vnode.h>
#include <sys/signalvar.h>
#include <sys/syslog.h>
#include <sys/timetc.h>
#include <sys/timex.h>
#include <sys/kauth.h>
#include <sys/mount.h>
#include <sys/syscallargs.h>
#include <sys/cpu.h>
kmutex_t itimer_mutex __cacheline_aligned; /* XXX static */
static struct itlist itimer_realtime_changed_notify;
static void ptimer_intr(void *);
static void *ptimer_sih __read_mostly;
static TAILQ_HEAD(, ptimer) ptimer_queue;
#define CLOCK_VIRTUAL_P(clockid) \
((clockid) == CLOCK_VIRTUAL || (clockid) == CLOCK_PROF)
CTASSERT(ITIMER_REAL == CLOCK_REALTIME);
CTASSERT(ITIMER_VIRTUAL == CLOCK_VIRTUAL);
CTASSERT(ITIMER_PROF == CLOCK_PROF);
CTASSERT(ITIMER_MONOTONIC == CLOCK_MONOTONIC);
#define DELAYTIMER_MAX 32
/*
* Initialize timekeeping.
*/
void
time_init(void)
{
mutex_init(&itimer_mutex, MUTEX_DEFAULT, IPL_SCHED);
LIST_INIT(&itimer_realtime_changed_notify);
TAILQ_INIT(&ptimer_queue);
ptimer_sih = softint_establish(SOFTINT_CLOCK | SOFTINT_MPSAFE,
ptimer_intr, NULL);
}
/*
* Check if the time will wrap if set to ts.
*
* ts - timespec describing the new time
* delta - the delta between the current time and ts
*/
bool
time_wraps(struct timespec *ts, struct timespec *delta)
{
/*
* Don't allow the time to be set forward so far it
* will wrap and become negative, thus allowing an
* attacker to bypass the next check below. The
* cutoff is 1 year before rollover occurs, so even
* if the attacker uses adjtime(2) to move the time
* past the cutoff, it will take a very long time
* to get to the wrap point.
*/
if ((ts->tv_sec > LLONG_MAX - 365*24*60*60) ||
(delta->tv_sec < 0 || delta->tv_nsec < 0))
return true;
return false;
}
/*
* itimer_lock:
*
* Acquire the interval timer data lock.
*/
void
itimer_lock(void)
{
mutex_spin_enter(&itimer_mutex);
}
/*
* itimer_unlock:
*
* Release the interval timer data lock.
*/
void
itimer_unlock(void)
{
mutex_spin_exit(&itimer_mutex);
}
/*
* itimer_lock_held:
*
* Check that the interval timer lock is held for diagnostic
* assertions.
*/
inline bool __diagused
itimer_lock_held(void)
{
return mutex_owned(&itimer_mutex);
}
/*
* Time of day and interval timer support.
*
* These routines provide the kernel entry points to get and set
* the time-of-day and per-process interval timers. Subroutines
* here provide support for adding and subtracting timeval structures
* and decrementing interval timers, optionally reloading the interval
* timers when they expire.
*/
/* This function is used by clock_settime and settimeofday */
static int
settime1(struct proc *p, const struct timespec *ts, bool check_kauth)
{
struct timespec delta, now;
/*
* The time being set to an unreasonable value will cause
* unreasonable system behaviour.
*/
if (ts->tv_sec < 0 || ts->tv_sec > (1LL << 36))
return (EINVAL);
nanotime(&now);
timespecsub(ts, &now, &delta);
if (check_kauth && kauth_authorize_system(kauth_cred_get(),
KAUTH_SYSTEM_TIME, KAUTH_REQ_SYSTEM_TIME_SYSTEM, __UNCONST(ts),
&delta, KAUTH_ARG(check_kauth ? false : true)) != 0) {
return (EPERM);
}
#ifdef notyet
if ((delta.tv_sec < 86400) && securelevel > 0) { /* XXX elad - notyet */
return (EPERM);
}
#endif
tc_setclock(ts);
resettodr();
/*
* Notify pending CLOCK_REALTIME timers about the real time change.
* There may be inactive timers on this list, but this happens
* comparatively less often than timers firing, and so it's better
* to put the extra checks here than to complicate the other code
* path.
*/
struct itimer *it;
itimer_lock();
LIST_FOREACH(it, &itimer_realtime_changed_notify, it_rtchgq) {
KASSERT(it->it_ops->ito_realtime_changed != NULL);
if (timespecisset(&it->it_time.it_value)) {
(*it->it_ops->ito_realtime_changed)(it);
}
}
itimer_unlock();
return (0);
}
int
settime(struct proc *p, struct timespec *ts)
{
return (settime1(p, ts, true));
}
/* ARGSUSED */
int
sys___clock_gettime50(struct lwp *l,
const struct sys___clock_gettime50_args *uap, register_t *retval)
{
/* {
syscallarg(clockid_t) clock_id;
syscallarg(struct timespec *) tp;
} */
int error;
struct timespec ats;
error = clock_gettime1(SCARG(uap, clock_id), &ats);
if (error != 0)
return error;
return copyout(&ats, SCARG(uap, tp), sizeof(ats));
}
/* ARGSUSED */
int
sys___clock_settime50(struct lwp *l,
const struct sys___clock_settime50_args *uap, register_t *retval)
{
/* {
syscallarg(clockid_t) clock_id;
syscallarg(const struct timespec *) tp;
} */
int error;
struct timespec ats;
if ((error = copyin(SCARG(uap, tp), &ats, sizeof(ats))) != 0)
return error;
return clock_settime1(l->l_proc, SCARG(uap, clock_id), &ats, true);
}
int
clock_settime1(struct proc *p, clockid_t clock_id, const struct timespec *tp,
bool check_kauth)
{
int error;
if (tp->tv_nsec < 0 || tp->tv_nsec >= 1000000000L)
return EINVAL;
switch (clock_id) {
case CLOCK_REALTIME:
if ((error = settime1(p, tp, check_kauth)) != 0)
return (error);
break;
case CLOCK_MONOTONIC:
return (EINVAL); /* read-only clock */
default:
return (EINVAL);
}
return 0;
}
int
sys___clock_getres50(struct lwp *l, const struct sys___clock_getres50_args *uap,
register_t *retval)
{
/* {
syscallarg(clockid_t) clock_id;
syscallarg(struct timespec *) tp;
} */
struct timespec ts;
int error;
if ((error = clock_getres1(SCARG(uap, clock_id), &ts)) != 0)
return error;
if (SCARG(uap, tp))
error = copyout(&ts, SCARG(uap, tp), sizeof(ts));
return error;
}
int
clock_getres1(clockid_t clock_id, struct timespec *ts)
{
switch (clock_id) {
case CLOCK_REALTIME:
case CLOCK_MONOTONIC:
ts->tv_sec = 0;
if (tc_getfrequency() > 1000000000)
ts->tv_nsec = 1;
else
ts->tv_nsec = 1000000000 / tc_getfrequency();
break;
default:
return EINVAL;
}
return 0;
}
/* ARGSUSED */
int
sys___nanosleep50(struct lwp *l, const struct sys___nanosleep50_args *uap,
register_t *retval)
{
/* {
syscallarg(struct timespec *) rqtp;
syscallarg(struct timespec *) rmtp;
} */
struct timespec rmt, rqt;
int error, error1;
error = copyin(SCARG(uap, rqtp), &rqt, sizeof(struct timespec));
if (error)
return (error);
error = nanosleep1(l, CLOCK_MONOTONIC, 0, &rqt,
SCARG(uap, rmtp) ? &rmt : NULL);
if (SCARG(uap, rmtp) == NULL || (error != 0 && error != EINTR))
return error;
error1 = copyout(&rmt, SCARG(uap, rmtp), sizeof(rmt));
return error1 ? error1 : error;
}
/* ARGSUSED */
int
sys_clock_nanosleep(struct lwp *l, const struct sys_clock_nanosleep_args *uap,
register_t *retval)
{
/* {
syscallarg(clockid_t) clock_id;
syscallarg(int) flags;
syscallarg(struct timespec *) rqtp;
syscallarg(struct timespec *) rmtp;
} */
struct timespec rmt, rqt;
int error, error1;
error = copyin(SCARG(uap, rqtp), &rqt, sizeof(struct timespec));
if (error)
goto out;
error = nanosleep1(l, SCARG(uap, clock_id), SCARG(uap, flags), &rqt,
SCARG(uap, rmtp) ? &rmt : NULL);
if (SCARG(uap, rmtp) == NULL || (error != 0 && error != EINTR))
goto out;
if ((SCARG(uap, flags) & TIMER_ABSTIME) == 0 &&
(error1 = copyout(&rmt, SCARG(uap, rmtp), sizeof(rmt))) != 0)
error = error1;
out:
*retval = error;
return 0;
}
int
nanosleep1(struct lwp *l, clockid_t clock_id, int flags, struct timespec *rqt,
struct timespec *rmt)
{
struct timespec rmtstart;
int error, timo;
if ((error = ts2timo(clock_id, flags, rqt, &timo, &rmtstart)) != 0) {
if (error == ETIMEDOUT) {
error = 0;
if (rmt != NULL)
rmt->tv_sec = rmt->tv_nsec = 0;
}
return error;
}
/*
* Avoid inadvertently sleeping forever
*/
if (timo == 0)
timo = 1;
again:
error = kpause("nanoslp", true, timo, NULL);
if (error == EWOULDBLOCK)
error = 0;
if (rmt != NULL || error == 0) {
struct timespec rmtend;
struct timespec t0;
struct timespec *t;
int err;
err = clock_gettime1(clock_id, &rmtend);
if (err != 0)
return err;
t = (rmt != NULL) ? rmt : &t0;
if (flags & TIMER_ABSTIME) {
timespecsub(rqt, &rmtend, t);
} else {
if (timespeccmp(&rmtend, &rmtstart, <))
timespecclear(t); /* clock wound back */
else
timespecsub(&rmtend, &rmtstart, t);
if (timespeccmp(rqt, t, <))
timespecclear(t);
else
timespecsub(rqt, t, t);
}
if (t->tv_sec < 0)
timespecclear(t);
if (error == 0) {
timo = tstohz(t);
if (timo > 0)
goto again;
}
}
if (error == ERESTART)
error = EINTR;
return error;
}
int
sys_clock_getcpuclockid2(struct lwp *l,
const struct sys_clock_getcpuclockid2_args *uap,
register_t *retval)
{
/* {
syscallarg(idtype_t idtype;
syscallarg(id_t id);
syscallarg(clockid_t *)clock_id;
} */
pid_t pid;
lwpid_t lid;
clockid_t clock_id;
id_t id = SCARG(uap, id);
switch (SCARG(uap, idtype)) {
case P_PID:
pid = id == 0 ? l->l_proc->p_pid : id;
clock_id = CLOCK_PROCESS_CPUTIME_ID | pid;
break;
case P_LWPID:
lid = id == 0 ? l->l_lid : id;
clock_id = CLOCK_THREAD_CPUTIME_ID | lid;
break;
default:
return EINVAL;
}
return copyout(&clock_id, SCARG(uap, clock_id), sizeof(clock_id));
}
/* ARGSUSED */
int
sys___gettimeofday50(struct lwp *l, const struct sys___gettimeofday50_args *uap,
register_t *retval)
{
/* {
syscallarg(struct timeval *) tp;
syscallarg(void *) tzp; really "struct timezone *";
} */
struct timeval atv;
int error = 0;
struct timezone tzfake;
if (SCARG(uap, tp)) {
memset(&atv, 0, sizeof(atv));
microtime(&atv);
error = copyout(&atv, SCARG(uap, tp), sizeof(atv));
if (error)
return (error);
}
if (SCARG(uap, tzp)) {
/*
* NetBSD has no kernel notion of time zone, so we just
* fake up a timezone struct and return it if demanded.
*/
tzfake.tz_minuteswest = 0;
tzfake.tz_dsttime = 0;
error = copyout(&tzfake, SCARG(uap, tzp), sizeof(tzfake));
}
return (error);
}
/* ARGSUSED */
int
sys___settimeofday50(struct lwp *l, const struct sys___settimeofday50_args *uap,
register_t *retval)
{
/* {
syscallarg(const struct timeval *) tv;
syscallarg(const void *) tzp; really "const struct timezone *";
} */
return settimeofday1(SCARG(uap, tv), true, SCARG(uap, tzp), l, true);
}
int
settimeofday1(const struct timeval *utv, bool userspace,
const void *utzp, struct lwp *l, bool check_kauth)
{
struct timeval atv;
struct timespec ts;
int error;
/* Verify all parameters before changing time. */
/*
* NetBSD has no kernel notion of time zone, and only an
* obsolete program would try to set it, so we log a warning.
*/
if (utzp)
log(LOG_WARNING, "pid %d attempted to set the "
"(obsolete) kernel time zone\n", l->l_proc->p_pid);
if (utv == NULL)
return 0;
if (userspace) {
if ((error = copyin(utv, &atv, sizeof(atv))) != 0)
return error;
utv = &atv;
}
if (utv->tv_usec < 0 || utv->tv_usec >= 1000000)
return EINVAL;
TIMEVAL_TO_TIMESPEC(utv, &ts);
return settime1(l->l_proc, &ts, check_kauth);
}
int time_adjusted; /* set if an adjustment is made */
/* ARGSUSED */
int
sys___adjtime50(struct lwp *l, const struct sys___adjtime50_args *uap,
register_t *retval)
{
/* {
syscallarg(const struct timeval *) delta;
syscallarg(struct timeval *) olddelta;
} */
int error;
struct timeval atv, oldatv;
if ((error = kauth_authorize_system(l->l_cred, KAUTH_SYSTEM_TIME,
KAUTH_REQ_SYSTEM_TIME_ADJTIME, NULL, NULL, NULL)) != 0)
return error;
if (SCARG(uap, delta)) {
error = copyin(SCARG(uap, delta), &atv,
sizeof(*SCARG(uap, delta)));
if (error)
return (error);
}
adjtime1(SCARG(uap, delta) ? &atv : NULL,
SCARG(uap, olddelta) ? &oldatv : NULL, l->l_proc);
if (SCARG(uap, olddelta))
error = copyout(&oldatv, SCARG(uap, olddelta),
sizeof(*SCARG(uap, olddelta)));
return error;
}
void
adjtime1(const struct timeval *delta, struct timeval *olddelta, struct proc *p)
{
extern int64_t time_adjtime; /* in kern_ntptime.c */
if (olddelta) {
memset(olddelta, 0, sizeof(*olddelta));
mutex_spin_enter(&timecounter_lock);
olddelta->tv_sec = time_adjtime / 1000000;
olddelta->tv_usec = time_adjtime % 1000000;
if (olddelta->tv_usec < 0) {
olddelta->tv_usec += 1000000;
olddelta->tv_sec--;
}
mutex_spin_exit(&timecounter_lock);
}
if (delta) {
mutex_spin_enter(&timecounter_lock);
/*
* XXX This should maybe just report failure to
* userland for nonsense deltas.
*/
if (delta->tv_sec > INT64_MAX/1000000 - 1) {
time_adjtime = INT64_MAX;
} else if (delta->tv_sec < INT64_MIN/1000000 + 1) {
time_adjtime = INT64_MIN;
} else {
time_adjtime = delta->tv_sec * 1000000
+ MAX(-999999, MIN(999999, delta->tv_usec));
}
if (time_adjtime) {
/* We need to save the system time during shutdown */
time_adjusted |= 1;
}
mutex_spin_exit(&timecounter_lock);
}
}
/*
* Interval timer support.
*
* The itimer_*() routines provide generic support for interval timers,
* both real (CLOCK_REALTIME, CLOCK_MONOTIME), and virtual (CLOCK_VIRTUAL,
* CLOCK_PROF).
*
* Real timers keep their deadline as an absolute time, and are fired
* by a callout. Virtual timers are kept as a linked-list of deltas,
* and are processed by hardclock().
*
* Because the real time timer callout may be delayed in real time due
* to interrupt processing on the system, it is possible for the real
* time timeout routine (itimer_callout()) run past after its deadline.
* It does not suffice, therefore, to reload the real timer .it_value
* from the timer's .it_interval. Rather, we compute the next deadline
* in absolute time based on the current time and the .it_interval value,
* and report any overruns.
*
* Note that while the virtual timers are supported in a generic fashion
* here, they only (currently) make sense as per-process timers, and thus
* only really work for that case.
*/
/*
* itimer_init:
*
* Initialize the common data for an interval timer.
*/
void
itimer_init(struct itimer * const it, const struct itimer_ops * const ops,
clockid_t const id, struct itlist * const itl)
{
KASSERT(itimer_lock_held());
KASSERT(ops != NULL);
timespecclear(&it->it_time.it_value);
it->it_ops = ops;
it->it_clockid = id;
it->it_overruns = 0;
it->it_dying = false;
if (!CLOCK_VIRTUAL_P(id)) {
KASSERT(itl == NULL);
callout_init(&it->it_ch, CALLOUT_MPSAFE);
if (id == CLOCK_REALTIME && ops->ito_realtime_changed != NULL) {
LIST_INSERT_HEAD(&itimer_realtime_changed_notify,
it, it_rtchgq);
}
} else {
KASSERT(itl != NULL);
it->it_vlist = itl;
it->it_active = false;
}
}
/*
* itimer_poison:
*
* Poison an interval timer, preventing it from being scheduled
* or processed, in preparation for freeing the timer.
*/
void
itimer_poison(struct itimer * const it)
{
KASSERT(itimer_lock_held());
it->it_dying = true;
/*
* For non-virtual timers, stop the callout, or wait for it to
* run if it has already fired. It cannot restart again after
* this point: the callout won't restart itself when dying, no
* other users holding the lock can restart it, and any other
* users waiting for callout_halt concurrently (itimer_settime)
* will restart from the top.
*/
if (!CLOCK_VIRTUAL_P(it->it_clockid)) {
callout_halt(&it->it_ch, &itimer_mutex);
if (it->it_clockid == CLOCK_REALTIME &&
it->it_ops->ito_realtime_changed != NULL) {
LIST_REMOVE(it, it_rtchgq);
}
}
}
/*
* itimer_fini:
*
* Release resources used by an interval timer.
*
* N.B. itimer_lock must be held on entry, and is released on exit.
*/
void
itimer_fini(struct itimer * const it)
{
KASSERT(itimer_lock_held());
/* All done with the global state. */
itimer_unlock();
/* Destroy the callout, if needed. */
if (!CLOCK_VIRTUAL_P(it->it_clockid))
callout_destroy(&it->it_ch);
}
/*
* itimer_decr:
*
* Decrement an interval timer by a specified number of nanoseconds,
* which must be less than a second, i.e. < 1000000000. If the timer
* expires, then reload it. In this case, carry over (nsec - old value)
* to reduce the value reloaded into the timer so that the timer does
* not drift. This routine assumes that it is called in a context where
* the timers on which it is operating cannot change in value.
*
* Returns true if the timer has expired.
*/
static bool
itimer_decr(struct itimer *it, int nsec)
{
struct itimerspec *itp;
int error __diagused;
KASSERT(itimer_lock_held());
KASSERT(CLOCK_VIRTUAL_P(it->it_clockid));
itp = &it->it_time;
if (itp->it_value.tv_nsec < nsec) {
if (itp->it_value.tv_sec == 0) {
/* expired, and already in next interval */
nsec -= itp->it_value.tv_nsec;
goto expire;
}
itp->it_value.tv_nsec += 1000000000;
itp->it_value.tv_sec--;
}
itp->it_value.tv_nsec -= nsec;
nsec = 0;
if (timespecisset(&itp->it_value))
return false;
/* expired, exactly at end of interval */
expire:
if (timespecisset(&itp->it_interval)) {
itp->it_value = itp->it_interval;
itp->it_value.tv_nsec -= nsec;
if (itp->it_value.tv_nsec < 0) {
itp->it_value.tv_nsec += 1000000000;
itp->it_value.tv_sec--;
}
error = itimer_settime(it);
KASSERT(error == 0); /* virtual, never fails */
} else
itp->it_value.tv_nsec = 0; /* sec is already 0 */
return true;
}
static void itimer_callout(void *);
/*
* itimer_arm_real:
*
* Arm a non-virtual timer.
*/
static void
itimer_arm_real(struct itimer * const it)
{
/*
* Don't need to check tshzto() return value, here.
* callout_reset() does it for us.
*/
callout_reset(&it->it_ch,
(it->it_clockid == CLOCK_MONOTONIC
? tshztoup(&it->it_time.it_value)
: tshzto(&it->it_time.it_value)),
itimer_callout, it);
}
/*
* itimer_callout:
*
* Callout to expire a non-virtual timer. Queue it up for processing,
* and then reload, if it is configured to do so.
*
* N.B. A delay in processing this callout causes multiple
* SIGALRM calls to be compressed into one.
*/
static void
itimer_callout(void *arg)
{
uint64_t last_val, next_val, interval, now_ns;
struct timespec now, next;
struct itimer * const it = arg;
int backwards;
itimer_lock();
(*it->it_ops->ito_fire)(it);
if (!timespecisset(&it->it_time.it_interval)) {
timespecclear(&it->it_time.it_value);
itimer_unlock();
return;
}
if (it->it_clockid == CLOCK_MONOTONIC) {
getnanouptime(&now);
} else {
getnanotime(&now);
}
backwards = (timespeccmp(&it->it_time.it_value, &now, >));
timespecadd(&it->it_time.it_value, &it->it_time.it_interval, &next);
/* Handle the easy case of non-overflown timers first. */
if (!backwards && timespeccmp(&next, &now, >)) {
it->it_time.it_value = next;
} else {
now_ns = timespec2ns(&now);
last_val = timespec2ns(&it->it_time.it_value);
interval = timespec2ns(&it->it_time.it_interval);
next_val = now_ns +
(now_ns - last_val + interval - 1) % interval;
if (backwards)
next_val += interval;
else
it->it_overruns += (now_ns - last_val) / interval;
it->it_time.it_value.tv_sec = next_val / 1000000000;
it->it_time.it_value.tv_nsec = next_val % 1000000000;
}
/*
* Reset the callout, if it's not going away.
*/
if (!it->it_dying)
itimer_arm_real(it);
itimer_unlock();
}
/*
* itimer_settime:
*
* Set up the given interval timer. The value in it->it_time.it_value
* is taken to be an absolute time for CLOCK_REALTIME/CLOCK_MONOTONIC
* timers and a relative time for CLOCK_VIRTUAL/CLOCK_PROF timers.
*
* If the callout had already fired but not yet run, fails with
* ERESTART -- caller must restart from the top to look up a timer.
*/
int
itimer_settime(struct itimer *it)
{
struct itimer *itn, *pitn;
struct itlist *itl;
KASSERT(itimer_lock_held());
if (!CLOCK_VIRTUAL_P(it->it_clockid)) {
/*
* Try to stop the callout. However, if it had already
* fired, we have to drop the lock to wait for it, so
* the world may have changed and pt may not be there
* any more. In that case, tell the caller to start
* over from the top.
*/
if (callout_halt(&it->it_ch, &itimer_mutex))
return ERESTART;
/* Now we can touch it and start it up again. */
if (timespecisset(&it->it_time.it_value))
itimer_arm_real(it);
} else {
if (it->it_active) {
itn = LIST_NEXT(it, it_list);
LIST_REMOVE(it, it_list);
for ( ; itn; itn = LIST_NEXT(itn, it_list))
timespecadd(&it->it_time.it_value,
&itn->it_time.it_value,
&itn->it_time.it_value);
}
if (timespecisset(&it->it_time.it_value)) {
itl = it->it_vlist;
for (itn = LIST_FIRST(itl), pitn = NULL;
itn && timespeccmp(&it->it_time.it_value,
&itn->it_time.it_value, >);
pitn = itn, itn = LIST_NEXT(itn, it_list))
timespecsub(&it->it_time.it_value,
&itn->it_time.it_value,
&it->it_time.it_value);
if (pitn)
LIST_INSERT_AFTER(pitn, it, it_list);
else
LIST_INSERT_HEAD(itl, it, it_list);
for ( ; itn ; itn = LIST_NEXT(itn, it_list))
timespecsub(&itn->it_time.it_value,
&it->it_time.it_value,
&itn->it_time.it_value);
it->it_active = true;
} else {
it->it_active = false;
}
}
/* Success! */
return 0;
}
/*
* itimer_gettime:
*
* Return the remaining time of an interval timer.
*/
void
itimer_gettime(const struct itimer *it, struct itimerspec *aits)
{
struct timespec now;
struct itimer *itn;
KASSERT(itimer_lock_held());
*aits = it->it_time;
if (!CLOCK_VIRTUAL_P(it->it_clockid)) {
/*
* Convert from absolute to relative time in .it_value
* part of real time timer. If time for real time
* timer has passed return 0, else return difference
* between current time and time for the timer to go
* off.
*/
if (timespecisset(&aits->it_value)) {
if (it->it_clockid == CLOCK_REALTIME) {
getnanotime(&now);
} else { /* CLOCK_MONOTONIC */
getnanouptime(&now);
}
if (timespeccmp(&aits->it_value, &now, <))
timespecclear(&aits->it_value);
else
timespecsub(&aits->it_value, &now,
&aits->it_value);
}
} else if (it->it_active) {
for (itn = LIST_FIRST(it->it_vlist); itn && itn != it;
itn = LIST_NEXT(itn, it_list))
timespecadd(&aits->it_value,
&itn->it_time.it_value, &aits->it_value);
KASSERT(itn != NULL); /* it should be findable on the list */
} else
timespecclear(&aits->it_value);
}
/*
* Per-process timer support.