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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
//! Linux's coalescing of POSIX interval timers, with overruns, on the traced
//! path (<https://github.com/rrnewton/hermit/issues/4262>).
//!
//! Linux queues a POSIX timer's expiry as the timer's own preallocated entry,
//! beside any ordinary copy of the same standard signal, and stops a periodic
//! timer until that entry is dequeued (`posix_timer_fn` returns
//! `HRTIMER_NORESTART`). The dequeue re-arms it on its grid
//! (`hrtimer_forward_now`) and reports the missed periods as `si_overrun`; an
//! entry whose timer was set again since it was queued is dropped inside the
//! dequeue. Before this, the traced path re-armed every expiry at the old
//! deadline plus one interval, so a slice that crossed N periods fired N
//! signals in a burst, and each send merged into the one pending copy.
//!
//! In an observable (process, signal) pair (`signal_observable`) the
//! scheduler keeps the entries Linux would hold (`signal_lists`), sends only
//! the front of each list, and at each dequeue it sees (a reported delivery
//! stop, a take, an unreported pass) pops the front, re-arms its timer and
//! sends the next one (promotion). Every other pair takes the fallback: each
//! expiry is sent at its pop with the overrun counted then, and the timer
//! forwards to its next grid point.
//!
//! Record and replay keep the legacy recurrence (`coalesces_alarms`).
use nix::sys::signal::Signal;
use serde::Deserialize;
use serde::Serialize;
use tracing::debug;
use tracing::info;
use super::Scheduler;
use super::discarded_at_send::Consumption;
use super::discarded_at_send::QueueId;
use super::discarded_at_send::SendFate;
use super::discarded_at_send::SignalProducer;
use super::kernel_signal_bit;
use super::signal_lists::Entry;
use super::signal_lists::FrontClass;
use super::signal_lists::KernelSiginfo;
use super::signal_lists::Popped;
use super::signal_lists::TimerAppend;
use super::signal_lists::TimerEntry;
use super::signal_lists::timer_siginfo;
use super::timed_waiters::AlarmPhase;
use super::timed_waiters::SignalTarget;
use super::timed_waiters::SignalTimerId;
use super::timed_waiters::grid_after;
use crate::types::DetPid;
use crate::types::DetTid;
use crate::types::LogicalTime;
/// The signals whose pairs are never observable (4262 design §3.4): those the
/// kernel raises itself, the job-control signals, which any sender's stop or
/// SIGCONT flushes, Reverie's timer signal, and SIGKILL.
const EXCLUDED_SIGNALS: [i32; 15] = [
libc::SIGPIPE,
libc::SIGXFSZ,
libc::SIGSYS,
libc::SIGSEGV,
libc::SIGBUS,
libc::SIGILL,
libc::SIGFPE,
libc::SIGTRAP,
libc::SIGCONT,
libc::SIGSTOP,
libc::SIGTSTP,
libc::SIGTTIN,
libc::SIGTTOU,
libc::SIGSTKFLT,
libc::SIGKILL,
];
/// What a reported delivery stop does with the signal it dequeued
/// (`Scheduler::timer_signal_dequeue`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DeliveryAnswer {
/// Deliver the physical record as it is.
AsIs,
/// Deliver it with this siginfo (`Guest::set_signal_info`).
Rewrite(KernelSiginfo),
/// Linux skips this entry inside the dequeue: deliver nothing.
Suppress,
/// A valid timer entry: deliver it with its own siginfo, asked for once
/// the delivery's turn is granted (`Scheduler::timer_delivery_info`), so
/// its overrun is counted at the time its handler begins.
TimerEntry,
}
/// What a take (`rt_sigtimedwait`, a signalfd record) does with the copy it
/// took (`Scheduler::timer_signal_take`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct TakeOutcome {
/// Drop it and take again, as if it had never been queued: a copy Linux
/// discarded when it was sent, or a stale timer entry Linux skips inside
/// the dequeue.
pub skip: bool,
/// Return it with this siginfo instead of the physical record's.
pub rewrite: Option<KernelSiginfo>,
}
/// A dequeue identified at a reported stop, popped once the stop's hooks
/// have read the queues (`Scheduler::finish_timer_signal_dequeue`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct PendingDequeue {
queue: QueueId,
signal: i32,
/// A delivery, after which the receiver runs the signal's handler, if
/// it has one, with that handler's mask (not a take).
delivery: bool,
/// For a valid timer entry: the timer, the consuming thread's time, and
/// the overrun its delivery reports.
reconcile: Option<(i32, LogicalTime, i32)>,
/// A valid timer entry whose siginfo the delivery's turn has yet to ask
/// for (`DeliveryAnswer::TimerEntry`), with its timer's state as the stop
/// found it.
awaiting_info: Option<CapturedEntry>,
/// The front this dequeue took, popped before the stop's hooks ran
/// because a send found the kernel's queue already without it
/// (`Scheduler::pop_in_flight_front`).
early: Option<Popped>,
}
/// A timer entry as a delivery stop dequeued it: its `si_value` and, for a
/// periodic timer waiting for this dequeue, its last expiry and interval.
/// Linux fills the siginfo at the dequeue, so a `timer_settime` or
/// `timer_delete` another thread commits before the delivery's turn does not
/// change it (the Claude review of https://github.com/rrnewton/hermit/pull/4491,
/// P3-5).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct CapturedEntry {
entry: TimerEntry,
value: u64,
grid: Option<(LogicalTime, LogicalTime)>,
}
/// End the run with a named refusal (`exit_on_scheduler_refusal`); a unit
/// test sees it as a panic with the same text.
fn refuse(refusal: std::fmt::Arguments<'_>) -> ! {
#[cfg(test)]
panic!("{refusal}");
#[cfg(not(test))]
super::exit_on_scheduler_refusal(&refusal)
}
/// The overrun a captured entry's delivery at `at` reports.
fn captured_overrun(captured: &CapturedEntry, at: LogicalTime) -> i32 {
captured
.grid
.map_or(0, |(last, interval)| overrun_at(last, interval, at))
}
/// The overrun Linux reports for a periodic timer last expired at `last`
/// with `interval`, dequeued at `t`: `hrtimer_forward_now` moves the expiry
/// past `t` by k intervals, and `it_overrun_last` is k - 1, clamped to
/// `INT_MAX` (`timer_overrun_to_int`).
pub(crate) fn overrun_at(last: LogicalTime, interval: LogicalTime, t: LogicalTime) -> i32 {
let interval_ns = interval.as_nanos().max(1);
// k - 1, the whole intervals elapsed since `last`.
let missed = t.as_nanos().saturating_sub(last.as_nanos()) / interval_ns;
i32::try_from(missed).unwrap_or(i32::MAX)
}
impl Scheduler {
/// Record what `timer_settime` or `timer_delete` of `process`'s timer
/// `timer` says: its `si_value`, a set's reset of the overrun
/// (`do_timer_settime`), and that `process` has a timer on `signo`
/// (`DiscardedAtSend::note_timer_history`). A delete removes the timer's
/// park (`timer_delete`), and its value, which marks it deleted.
pub(crate) fn note_posix_timer_notification(
&mut self,
process: DetPid,
timer: i32,
signo: i32,
value: u64,
deleted: bool,
) {
if deleted {
self.posix_timer_values.remove(&(process, timer));
self.posix_timer_overruns.remove(&(process, timer));
self.discarded_at_send.forget_park(process, timer);
return;
}
self.posix_timer_values.insert((process, timer), value);
self.posix_timer_overruns.insert((process, timer), 0);
super::TIMER_COPIES_RECORDED.store(true, std::sync::atomic::Ordering::SeqCst);
if (1..32).contains(&signo) {
self.discarded_at_send.note_timer_history(process, signo);
}
}
/// A successful exec of `process` deleted its POSIX timers (`exit_itimers`).
pub(crate) fn delete_exec_posix_timers(&mut self, process: DetPid) {
self.blocked.timed_waiters.remove_posix_timers(process);
self.posix_timer_values
.retain(|(owner, _), _| *owner != process);
self.posix_timer_overruns
.retain(|(owner, _), _| *owner != process);
// Exec resets every caught signal's action (`flush_signal_handlers`).
self.handler_masks.retain(|(owner, _), _| *owner != process);
}
/// Whether `process`'s timer `timer` is live (created and not deleted).
fn posix_timer_live(&self, process: DetPid, timer: i32) -> bool {
self.posix_timer_values.contains_key(&(process, timer))
}
/// The entry an expiry of `process`'s timer `timer` would queue now: its
/// current generation and periodicity.
pub(super) fn timer_entry_now(&self, process: DetPid, timer: i32) -> TimerEntry {
TimerEntry {
process,
timer,
gen_at_send: self.posix_timer_arm_generation(process, timer),
periodic_at_send: self
.blocked
.timed_waiters
.signal_timer_period(SignalTimerId::Posix(process, timer))
.is_some(),
}
}
/// Whether `entry` is current: its timer was not set or deleted since it
/// was sent (Linux's `it_signal_seq == it_sigqueue_seq`).
pub(super) fn timer_entry_valid(&self, entry: &TimerEntry) -> bool {
self.posix_timer_live(entry.process, entry.timer)
&& entry.gen_at_send == self.posix_timer_arm_generation(entry.process, entry.timer)
}
/// Whether the scheduler sees every dequeue of `signal` in `process` at a
/// committed point (4262 design §3.4). Sticky once false; the first
/// false answer is a transition (`lose_timer_observability`).
pub(crate) fn signal_observable(&mut self, process: DetPid, signal: i32) -> bool {
if !self.coalesces_alarms()
|| !(1..32).contains(&signal)
|| EXCLUDED_SIGNALS.contains(&signal)
{
return false;
}
if self.signal_unobservable.contains(&(process, signal)) {
return false;
}
let bit = kernel_signal_bit(signal);
let threads = self.process_signal_targets(process);
let leader = DetTid::from_raw(process.as_raw());
let host_timed = threads
.iter()
.any(|thread| self.host_timed_signals(*thread) & bit != 0);
let child_exit = self
.thread_tree
.unreaped_children_of(process)
.into_iter()
.filter_map(|child| self.thread_tree.notification_signal(child))
.any(|exit_signal| exit_signal == signal);
let real_timer =
signal == libc::SIGALRM && self.blocked.timed_waiters.alarm_phase(process).is_some();
let observable = !self.background_call_processes.contains(&process)
&& !host_timed
&& !child_exit
&& !real_timer
&& threads.contains(&leader);
if !observable {
self.lose_timer_observability(process, signal);
}
observable
}
/// `signal` of `process` stops being observable (4262 design §4.11). A
/// list holding a single valid entry that is its own physical record (or
/// a `Plain` one that is not a `Proxy`), with no current park of the
/// signal, falls back: the lists go, and the physical record is delivered
/// as it stands. Anything else is refused by name, before any producer
/// the scheduler cannot see runs.
pub(crate) fn lose_timer_observability(&mut self, process: DetPid, signal: i32) {
if !self.signal_unobservable.insert((process, signal)) {
return;
}
debug!(
"[dpid {}] signal {}: timer entries are not observable from here on; expiries take the fallback.",
process, signal
);
for queue in self.process_queues(process) {
let entries = self.discarded_at_send.lists.entries(queue, signal);
let Some((front, class, _)) = self.discarded_at_send.lists.front(queue, signal) else {
continue;
};
let single_own = entries.len() == 1
&& class == FrontClass::Own
&& match front {
Entry::Plain { .. } => true,
Entry::Timer(timer) => self.timer_entry_valid(&timer),
};
if !single_own {
refuse(format_args!(
"hermit: signal {signal} of process {process} stopped being observable (a call outside the schedule, a host-timed source, or a child's exit signal) while its pending entries in {queue:?} were {entries:?} with a {class:?} front: Linux would deliver them one by one, which the fallback cannot, so the run is refused (https://github.com/rrnewton/hermit/issues/4262)"
));
}
self.discarded_at_send.lists.take_all(queue, signal);
}
// A periodic timer that waited for the dequeue of the entry the lists
// held goes onto the fallback's recurrence now: no dequeue the
// scheduler sees will re-arm it (the Claude review of
// https://github.com/rrnewton/hermit/pull/4491, P1-1).
if let Ok(sig) = Signal::try_from(signal) {
let now = self.committed_time;
for id in self
.blocked
.timed_waiters
.inactive_posix_timers(process, sig)
{
let next = self.blocked.timed_waiters.signal_timer_rearm_after(id, now);
debug!(
"[dpid {}] {:?} waited for its entry's dequeue; on the fallback, re-armed at {:?}.",
process, id, next
);
}
}
if self
.discarded_at_send
.parked_timers(process, signal)
.iter()
.any(|producer| self.posix_timer_expiry_current(producer))
{
refuse(format_args!(
"hermit: signal {signal} of process {process} stopped being observable while a POSIX timer's ignored expiry of it is parked: Linux re-queues it when the signal stops being ignored, which the fallback cannot follow, so the run is refused (https://github.com/rrnewton/hermit/issues/4262)"
));
}
}
/// Under record and replay, a POSIX timer copy was sent into `queue` as
/// `signal` (`replayed_timer_copies`); one sent while a signalfd covers
/// the signal may be read at once.
pub(crate) fn note_replayed_timer_copy(&mut self, queue: QueueId, signal: i32) {
if !self.recordreplay_modes || !self.models_signal_targets {
return;
}
self.replayed_timer_copies.insert((queue, signal));
let bit = kernel_signal_bit(signal);
if self.signalfd_masks.values().any(|mask| mask & bit != 0) {
self.replay_unproven_copies.insert((queue, signal));
}
}
/// Under record and replay, a signalfd now covers `mask` in `process`
/// (`None`: any process, a signalfd's description being shareable): the
/// timer copies of those signals may be read.
pub(crate) fn note_replay_take_cover(&mut self, process: Option<DetPid>, mask: u64) {
if !self.recordreplay_modes {
return;
}
let covered: Vec<(QueueId, i32)> = self
.replayed_timer_copies
.iter()
.copied()
.filter(|(queue, signal)| {
let owner = match queue {
QueueId::Process(owner) => *owner,
QueueId::Thread(thread) => self.sigchld_process(*thread),
};
mask & kernel_signal_bit(*signal) != 0 && process.is_none_or(|p| p == owner)
})
.collect();
self.replay_unproven_copies.extend(covered);
}
/// Under record and replay, an exec by `caller` that survives as
/// `leader` destroyed every other thread of the group (`siblings`, the
/// former leader among them) with its own queue, and moved the caller's
/// queue to the leader's tid: the replay records move with it, so that
/// `replay_exec_refusal` finds them (the Codex re-review of
/// https://github.com/rrnewton/hermit/pull/4491, P1).
pub(crate) fn transfer_replay_copies(
&mut self,
caller: DetTid,
leader: DetTid,
siblings: &[DetTid],
) {
let destroyed =
|queue: &QueueId| matches!(queue, QueueId::Thread(t) if siblings.contains(t));
let rekey = |(queue, signal): (QueueId, i32)| match queue {
QueueId::Thread(t) if t == caller => (QueueId::Thread(leader), signal),
other => (other, signal),
};
for set in [
&mut self.replayed_timer_copies,
&mut self.replay_unproven_copies,
] {
*set = std::mem::take(set)
.into_iter()
.filter(|(queue, _)| !destroyed(queue))
.map(rekey)
.collect();
}
}
/// Under record and replay, an exec of `process` whose survivor is
/// `survivor`, with a signal pending that a timer copy may have been
/// taken for unobserved: a replayed take dequeues nothing, so replay would
/// flush another record than the recording did. Refused by name, as
/// before https://github.com/rrnewton/hermit/issues/4262 (the Claude
/// review of https://github.com/rrnewton/hermit/pull/4491, P1-2). The
/// process's records go either way.
pub(crate) fn replay_exec_refusal(
&mut self,
survivor: DetTid,
process: DetPid,
) -> Option<String> {
if !self.recordreplay_modes {
return None;
}
let (private, shared) = (QueueId::Thread(survivor), QueueId::Process(process));
let unproven: Vec<(QueueId, i32)> = self
.replay_unproven_copies
.iter()
.copied()
.filter(|(queue, _)| *queue == private || *queue == shared)
.collect();
self.replayed_timer_copies
.retain(|(queue, _)| *queue != private && *queue != shared);
self.replay_unproven_copies
.retain(|(queue, _)| *queue != private && *queue != shared);
if unproven.is_empty() {
return None;
}
let state = match self.read_sleeper_signal_state(survivor) {
Ok(state) => state,
Err(failure) => {
return Some(format!(
"the pending signals of thread {survivor} could not be read ({failure:?})"
));
}
};
unproven.into_iter().find_map(|(queue, signal)| {
let pending = match queue {
QueueId::Thread(_) => state.thread_pending,
QueueId::Process(_) => state.shared_pending,
};
(pending & kernel_signal_bit(signal) != 0).then(|| {
format!(
"signal {signal} is pending in {queue:?}, and under record and replay a POSIX timer's copy of it may have been read by a signalfd, which a replayed read does not dequeue, so the exec would replay another flush"
)
})
})
}
/// Under record and replay, a reported delivery of `signal` to `thread`
/// left its queues as read (`thread_holds`, `process_holds`): a timer
/// copy no longer there was taken where the schedule sees it.
pub(crate) fn note_replayed_copy_taken(
&mut self,
thread: DetTid,
signal: i32,
thread_holds: bool,
process_holds: bool,
) {
if !self.recordreplay_modes {
return;
}
let process = self.sigchld_process(thread);
for (queue, holds) in [
(QueueId::Thread(thread), thread_holds),
(QueueId::Process(process), process_holds),
] {
if !holds {
self.replayed_timer_copies.remove(&(queue, signal));
self.replay_unproven_copies.remove(&(queue, signal));
}
}
}
/// The processes with timer-signal entries or parked expiries.
pub(crate) fn processes_with_timer_entries(&self) -> Vec<DetPid> {
let mut processes: Vec<DetPid> = self
.discarded_at_send
.lists
.listed()
.into_iter()
.map(|(queue, _)| match queue {
QueueId::Process(process) => process,
QueueId::Thread(thread) => self.sigchld_process(thread),
})
.chain(self.discarded_at_send.parked_processes())
.collect();
processes.sort();
processes.dedup();
processes
}
/// `child` was created: its exit signal, posted to its wait parent when it
/// exits, ends that pair's observability (`signal_observable`).
pub(crate) fn child_ends_timer_observability(&mut self, child: DetPid) {
// A forked child copies its creator's actions.
if let Some(parent) = self.thread_tree.parent_process(&child) {
let inherited: Vec<_> = self
.handler_masks
.iter()
.filter(|((owner, _), _)| *owner == parent)
.map(|((_, signal), action)| (*signal, *action))
.collect();
for (signal, action) in inherited {
self.handler_masks.insert((child, signal), action);
}
}
if !self.coalesces_alarms() {
return;
}
let (Some(parent), Some(signal)) = (
self.thread_tree.parent_process(&child),
self.thread_tree.notification_signal(child),
) else {
return;
};
if (1..32).contains(&signal) {
self.lose_timer_observability(parent, signal);
}
}
/// A thread of `process` is granted a call outside the schedule: every
/// signal of it stops being observable (`signal_observable` reads
/// `background_call_processes`), and the transition is decided now,
/// before the call can run.
pub(crate) fn background_call_ends_timer_observability(&mut self, process: DetPid) {
if !self.coalesces_alarms() {
return;
}
for signal in 1..32 {
self.lose_timer_observability(process, signal);
}
}
/// Fire the expiry at `deadline` of POSIX timer `id`, notifying `target`
/// with `signal`, which `pop_if_before` has just popped (and, if
/// periodic, re-armed one interval later). Replaces that recurrence.
pub(super) fn fire_posix_timer(
&mut self,
deadline: LogicalTime,
id: SignalTimerId,
target: SignalTarget,
signal: Signal,
) {
let SignalTimerId::Posix(process, timer) = id else {
unreachable!("fire_posix_timer takes a POSIX timer");
};
let signo = signal as libc::c_int;
if !self.models_signal_targets {
// Elsewhere the scheduler cannot single out a thread's queue.
match target {
SignalTarget::Thread(thread) => self.fire_thread_timer(id, thread, signal),
SignalTarget::Process(tid) => {
let producer = self.posix_timer_producer(id);
self.fire_process_timer(process, tid, signal, producer, None);
}
}
return;
}
let now = self.committed_time;
if !self.coalesces_alarms() || !self.signal_observable(process, signo) {
self.fire_posix_timer_fallback(deadline, id, target, signal, now);
return;
}
if let SignalTarget::Thread(thread) = target
&& !self.process_signal_targets(process).contains(&thread)
{
// Its recurrence stands: each period pops and is dropped
// (disclosure 5).
info!(
"[dpid {}] Timer expired after its thread {} exited; dropped.",
process, thread
);
return;
}
let periodic = self.blocked.timed_waiters.signal_timer_period(id).is_some();
// A periodic timer waits for the dequeue of its entry, or of its
// parked expiry's re-queued entry (`HRTIMER_NORESTART`).
if periodic {
self.blocked
.timed_waiters
.signal_timer_after_fire(id, deadline, Some(true), now);
}
let entry = self.timer_entry_now(process, timer);
let (queue, named, preferred) = match target {
SignalTarget::Thread(thread) => (QueueId::Thread(thread), thread, thread),
SignalTarget::Process(tid) => (
QueueId::Process(process),
DetTid::from_raw(process.as_raw()),
tid,
),
};
// Every expiry first refreshes the timer's queued entry (Linux sets
// `it_sigqueue_seq` and `it_sig_periodic` before ALREADY_PENDING).
let was_deliverable = self.list_deliverable(queue, signo);
if self.discarded_at_send.lists.refresh_timer(entry) {
info!(
"[dpid {}] POSIX timer {} expired with its entry still queued; refreshed.",
process, timer
);
if !was_deliverable && self.list_deliverable(queue, signo) {
self.wake_for_entry(queue, signal, preferred);
}
return;
}
if self.discarded_when_sent_to(named, signo, None) {
// Ignored: a periodic timer parks (4351's record keeps it, and the
// copy, which carries `SI_TIMER`); a one-shot is dropped.
let producer = periodic.then(|| self.posix_timer_producer(id)).flatten();
if producer.is_none() {
self.discarded_at_send.forget_park(process, timer);
}
let info = self.timer_signal_info(signo, &entry, 0);
self.send_timer_record(
queue,
signal,
preferred,
info,
SendFate::Classify(producer.map(SignalProducer::Posix)),
);
self.discarded_at_send.note_discarded_si_timer(
queue,
signo,
super::signal_lists::SI_TIMER,
);
return;
}
// A parked timer whose signal is now blocked goes back to the queue.
self.discarded_at_send.forget_park(process, timer);
let standing = self
.discarded_at_send
.is_discarded(queue, signo)
.then(|| self.discarded_at_send.discarded_is_si_timer(queue, signo));
match self
.discarded_at_send
.lists
.append_timer(queue, signo, entry, standing)
{
TimerAppend::SendFront | TimerAppend::ProxyFront => {
let info = self.timer_signal_info(signo, &entry, 0);
self.send_timer_record(queue, signal, preferred, info, SendFate::Kept);
}
TimerAppend::Behind => {
info!(
"[dpid {}] POSIX timer {} expired behind another entry of signal {}; queued.",
process, timer, signal
);
if !was_deliverable {
self.wake_for_entry(queue, signal, preferred);
}
}
TimerAppend::AlreadyPending => unreachable!("refreshed above"),
}
debug_assert!(self.discarded_at_send.lists.invariants_hold());
}
/// The fallback (4262 design §4.12): send the expiry at the pop, with
/// the overrun counted then, and forward the timer to its first grid
/// point after the pop.
fn fire_posix_timer_fallback(
&mut self,
deadline: LogicalTime,
id: SignalTimerId,
target: SignalTarget,
signal: Signal,
now: LogicalTime,
) {
let SignalTimerId::Posix(process, timer) = id else {
return;
};
let overrun = match self.blocked.timed_waiters.signal_timer_period(id) {
Some(interval) if self.coalesces_alarms() => {
self.blocked
.timed_waiters
.signal_timer_after_fire(id, deadline, None, now);
overrun_at(deadline, interval, now)
}
_ => 0,
};
if self.coalesces_alarms() {
self.posix_timer_overruns.insert((process, timer), overrun);
}
let entry = self.timer_entry_now(process, timer);
let info = self.timer_signal_info(signal as libc::c_int, &entry, overrun);
match target {
SignalTarget::Thread(thread) => self.fire_thread_timer(id, thread, signal),
SignalTarget::Process(tid) => {
let producer = self.posix_timer_producer(id);
self.fire_process_timer(process, tid, signal, producer, Some(info));
}
}
}
/// The `SI_TIMER` siginfo of `entry`'s delivery as `signal` with
/// `overrun`, as a 128-byte `siginfo_t`.
pub(crate) fn timer_signal_info(
&self,
signal: i32,
entry: &TimerEntry,
overrun: i32,
) -> [u8; 128] {
let value = self
.posix_timer_values
.get(&(entry.process, entry.timer))
.copied()
.unwrap_or(0);
timer_siginfo(signal, entry.timer, overrun, value).to_user()
}
/// Send a timer entry's physical record `info` into `queue` as `signal`:
/// a shared-queue send goes through `fire_process_alarm`, the one body
/// that keeps the shared-queue bookkeeping, preferring `preferred`; a
/// private one through `send_guest_signal`'s `rt_tgsigqueueinfo`.
fn send_timer_record(
&mut self,
queue: QueueId,
signal: Signal,
preferred: DetTid,
info: [u8; 128],
fate: SendFate,
) -> bool {
match queue {
QueueId::Process(process) => {
self.guest_send_landed = None;
let sent = self.fire_process_alarm(process, preferred, signal, Some(info), fate);
// Rule 4: a scheduler send of SIGALRM into the shared queue
// gives a copy-less Inactive ITIMER_REAL its copy
// (https://github.com/rrnewton/hermit/issues/4139).
if sent && signal == Signal::SIGALRM && self.guest_send_landed != Some(false) {
self.note_guest_sigalrm(
preferred,
super::itimer_coalesce::GuestSigalrmTarget::Process(process),
);
}
sent
}
QueueId::Thread(thread) => {
let process = self.sigchld_process(thread);
#[cfg(test)]
{
self.host_signal_attempts += 1;
}
self.send_guest_signal(thread, signal, Some(process), Some(info), thread, fate);
true
}
}
}
/// Whether (queue, signal) holds an entry a dequeue would deliver, or no
/// list at all (`SignalLists::deliverable`).
pub(super) fn list_deliverable(&self, queue: QueueId, signal: i32) -> bool {
self.discarded_at_send
.lists
.deliverable(queue, signal, |process, timer| {
if self.posix_timer_live(process, timer) {
self.posix_timer_arm_generation(process, timer)
} else {
u64::MAX
}
})
}
/// The single-target wake of a kept send of `signal` into `queue` that
/// needs no physical send (4262 design §4.13, rev 7 F): a timer entry
/// appended behind a stale head, or a stale entry refreshed in place.
/// The thread whose message caused it (an unignore's caller) is running,
/// so it is not woken (`signal_control_caller`).
pub(super) fn wake_for_entry(&mut self, queue: QueueId, signal: Signal, preferred: DetTid) {
let target = match queue {
QueueId::Thread(thread) => Some(thread),
QueueId::Process(process) => self
.select_signal_target(process, Some(preferred))
.map(|preferred| self.timer_signal_target(process, preferred, signal)),
};
let Some(target) = target else {
return;
};
if let QueueId::Process(process) = queue
&& self
.kernel_signal_target(process, target, signal as libc::c_int)
.is_none()
{
self.note_signal_left_in_shared_queue(process, signal as libc::c_int);
}
if self.signal_control_caller == Some(target) {
return;
}
self.wake_signaled_guest_as(target, signal, false);
}
/// At a reported delivery stop of `thread`, which dequeued `signal` at its
/// logical time `at`: identify the entry it took and answer what to
/// deliver (4262 design rev 8 A', §4.6 step 1). The signal is the one the
/// stop reports; the queue comes from the model, private first. With no
/// list for the signal in either queue, nothing is identified, and 4351's
/// record decides as before.
///
/// `at` is `None` for an unreported pass (4262 design §4.10), whose hook
/// cannot replace the siginfo and has no thread time: a valid entry
/// standing on its own record is delivered with that record (overrun 0,
/// disclosed) and its timer reconciled at the committed time, and one
/// standing on another sender's record is refused by name.
pub(crate) fn timer_signal_dequeue(
&mut self,
thread: DetTid,
signal: i32,
at: Option<LogicalTime>,
) -> DeliveryAnswer {
if let Some(unfinished) = self.pending_timer_dequeues.remove(&thread) {
self.retire_unfinished_dequeue(unfinished);
}
if !self.coalesces_alarms() || !(1..32).contains(&signal) {
return DeliveryAnswer::AsIs;
}
let process = self.sigchld_process(thread);
let Some(queue) = self.identify_listed_queue(thread, process, signal) else {
return DeliveryAnswer::AsIs;
};
let (front, class, _) = self
.discarded_at_send
.lists
.front(queue, signal)
.expect("an identified queue has a list");
let reported = at.is_some();
let at = at.unwrap_or(self.committed_time);
let stale = matches!(front, Entry::Timer(entry) if !self.timer_entry_valid(&entry));
if !reported && class == FrontClass::Proxy && !stale {
refuse(format_args!(
"hermit: thread {thread} took signal {signal} from {queue:?} where the backend passes it on unreported, so its siginfo cannot be replaced, and the pending record is another sender's standing for {front:?}: the guest would see that sender's siginfo, so the run is refused (https://github.com/rrnewton/hermit/issues/4262)"
));
}
let (answer, reconcile) = match front {
Entry::Plain { siginfo, .. } => match class {
FrontClass::Own => (DeliveryAnswer::AsIs, None),
FrontClass::Proxy => (DeliveryAnswer::Rewrite(siginfo), None),
},
Entry::Timer(_) if stale => (DeliveryAnswer::Suppress, None),
Entry::Timer(_) if reported => (DeliveryAnswer::TimerEntry, None),
Entry::Timer(entry) => {
let overrun = self.dequeue_overrun(&entry, at);
(DeliveryAnswer::AsIs, Some((entry.timer, at, overrun)))
}
};
let awaiting_info = match (answer, front) {
(DeliveryAnswer::TimerEntry, Entry::Timer(entry)) => Some(self.capture_entry(entry)),
_ => None,
};
self.pending_timer_dequeues.insert(
thread,
PendingDequeue {
queue,
signal,
delivery: true,
reconcile,
awaiting_info,
early: None,
},
);
answer
}
/// The siginfo of the valid timer entry `thread`'s delivery stop took
/// (`DeliveryAnswer::TimerEntry`), asked for once the delivery's turn is
/// granted, at the thread's time `at` then: Linux counts the overrun as it
/// dequeues, just before the handler runs, so it is counted where the
/// handler's time begins. Counted at the stop instead, it trailed the
/// handler's own clock by the delivery's turn: the T1 storm row measured
/// 197 against the 198 grid points the handler's clock showed.
pub(crate) fn timer_delivery_info(
&mut self,
thread: DetTid,
signal: i32,
at: LogicalTime,
) -> Option<KernelSiginfo> {
let pending = self.pending_timer_dequeues.get(&thread)?;
let captured = pending.awaiting_info.filter(|_| pending.signal == signal)?;
let at = at.max(self.committed_time);
let overrun = captured_overrun(&captured, at);
let pending = self.pending_timer_dequeues.get_mut(&thread)?;
pending.awaiting_info = None;
pending.reconcile = Some((captured.entry.timer, at, overrun));
Some(timer_siginfo(
signal,
captured.entry.timer,
overrun,
captured.value,
))
}
/// `entry` as a delivery stop dequeues it (`CapturedEntry`).
fn capture_entry(&self, entry: TimerEntry) -> CapturedEntry {
let id = SignalTimerId::Posix(entry.process, entry.timer);
let grid = match self.blocked.timed_waiters.signal_timer_state(id) {
Some((last, interval, AlarmPhase::Inactive { .. }))
if entry.periodic_at_send && interval != LogicalTime::ZERO =>
{
Some((last, interval))
}
_ => None,
};
CapturedEntry {
entry,
value: self
.posix_timer_values
.get(&(entry.process, entry.timer))
.copied()
.unwrap_or(0),
grid,
}
}
/// A take of `signal` by `thread` at its time `at` (4262 design §4.4,
/// rev 8 A'): the returned signal is authoritative. With no list for it
/// in either queue, 4351's record decides as before (`take_from`).
/// Otherwise the entry is identified from the model, private first,
/// checked against the queues read after the take, where read (the
/// identified queue's bit clear, the other queue's as its model says),
/// popped, its timer re-armed, and the next entry promoted before the
/// caller takes again.
pub(crate) fn timer_signal_take(
&mut self,
thread: DetTid,
signal: i32,
at: LogicalTime,
after: Option<(u64, u64)>,
) -> TakeOutcome {
// The take is in the caller's turn, granted at the committed time;
// the caller's own clock may not have caught up with it yet (a sleep
// it just woke from), and the overrun must not trail it.
let at = at.max(self.committed_time);
let process = self.sigchld_process(thread);
let listed = if self.coalesces_alarms() && (1..32).contains(&signal) {
self.identify_listed_queue(thread, process, signal)
} else {
None
};
let Some(queue) = listed else {
return TakeOutcome {
skip: self.discarded_at_send.take_from(thread, process, signal),
rewrite: None,
};
};
if let Some((thread_pending, shared_pending)) = after {
let bit = kernel_signal_bit(signal);
// A take dequeues in the caller's own turn: no send can follow
// the kernel's dequeue before this check.
self.check_taken_queues(
thread,
queue,
signal,
false,
thread_pending & bit != 0,
shared_pending & bit != 0,
);
}
let (front, class, _) = self
.discarded_at_send
.lists
.front(queue, signal)
.expect("an identified queue has a list");
let (outcome, reconcile) = match front {
Entry::Plain { siginfo, .. } => (
TakeOutcome {
skip: false,
rewrite: (class == FrontClass::Proxy).then_some(siginfo),
},
None,
),
Entry::Timer(entry) if !self.timer_entry_valid(&entry) => (
TakeOutcome {
skip: true,
rewrite: None,
},
None,
),
Entry::Timer(entry) => {
let overrun = self.dequeue_overrun(&entry, at);
let info = self.timer_signal_info(signal, &entry, overrun);
(
TakeOutcome {
skip: false,
rewrite: Some(KernelSiginfo::from_user(&info)),
},
Some((entry.timer, at, overrun)),
)
}
};
self.discarded_at_send.take(queue, signal);
self.pop_and_promote(
PendingDequeue {
queue,
signal,
delivery: false,
reconcile,
awaiting_info: None,
early: None,
},
thread,
);
outcome
}
/// A take for the signals `set` by `thread` at `at` failed copying out
/// the record it dequeued, which the kernel does not name; afterwards the
/// queues held `thread_pending` and `shared_pending` (rev 7 A3, rev 8 A',
/// N8-3). A listed (queue, signal) of the set whose bit is now clear is
/// the one taken: nothing else consumes in the caller's turn. With none,
/// the take was of an unlisted signal, which 4351's record decides
/// (`take_faulted`). Two such cannot be told apart, and refuse by name.
/// A stale entry is popped and the take repeats, as Linux would have
/// skipped it; a valid one is popped, re-armed and promoted, and the
/// fault stands. Returns whether to take again.
pub(crate) fn timer_signal_take_faulted(
&mut self,
thread: DetTid,
set: u64,
thread_pending: u64,
shared_pending: u64,
at: LogicalTime,
) -> bool {
let at = at.max(self.committed_time);
let process = self.sigchld_process(thread);
let (private, shared) = (QueueId::Thread(thread), QueueId::Process(process));
let mut taken = Vec::new();
if self.coalesces_alarms() {
for (queue, pending) in [(private, thread_pending), (shared, shared_pending)] {
for signal in 1..32 {
let bit = kernel_signal_bit(signal);
if set & bit != 0
&& pending & bit == 0
&& self.discarded_at_send.lists.is_listed(queue, signal)
{
taken.push((queue, signal));
}
}
}
}
let (queue, signal) = match taken.as_slice() {
[] => {
return self.discarded_at_send.take_faulted(
thread,
process,
set,
thread_pending,
shared_pending,
);
}
[one] => *one,
_ => refuse(format_args!(
"hermit: thread {thread}'s rt_sigtimedwait failed copying out a signal it dequeued, and the entries of {taken:?} all left their queues, so which one Linux took cannot be told; the run is refused (https://github.com/rrnewton/hermit/issues/4262)"
)),
};
let (front, _, _) = self
.discarded_at_send
.lists
.front(queue, signal)
.expect("a listed queue has a front");
let (skip, reconcile) = match front {
Entry::Timer(entry) if !self.timer_entry_valid(&entry) => (true, None),
Entry::Timer(entry) => {
let overrun = self.dequeue_overrun(&entry, at);
(false, Some((entry.timer, at, overrun)))
}
Entry::Plain { .. } => (false, None),
};
self.discarded_at_send.take(queue, signal);
self.pop_and_promote(
PendingDequeue {
queue,
signal,
delivery: false,
reconcile,
awaiting_info: None,
early: None,
},
thread,
);
skip
}
/// The listed queue a dequeue of `signal` by `thread` took from, private
/// first (Linux's `dequeue_signal`), or `None` when neither queue has a
/// list for it (the no-list branch) or the private queue's copy is a
/// discarded one with no list (4351 decides).
fn identify_listed_queue(
&self,
thread: DetTid,
process: DetPid,
signal: i32,
) -> Option<QueueId> {
let (private, shared) = (QueueId::Thread(thread), QueueId::Process(process));
let lists = &self.discarded_at_send.lists;
if !lists.is_listed(private, signal) && !lists.is_listed(shared, signal) {
return None;
}
let queue = if lists.is_listed(private, signal)
|| self.discarded_at_send.is_discarded(private, signal)
{
private
} else {
shared
};
lists.is_listed(queue, signal).then_some(queue)
}
/// The overrun a valid entry's delivery at `at` reports: for a periodic
/// timer waiting for this dequeue, the missed periods since its last
/// expiry; 0 for a one-shot.
fn dequeue_overrun(&self, entry: &TimerEntry, at: LogicalTime) -> i32 {
let id = SignalTimerId::Posix(entry.process, entry.timer);
match self.blocked.timed_waiters.signal_timer_state(id) {
Some((last, interval, AlarmPhase::Inactive { .. }))
if entry.periodic_at_send && interval != LogicalTime::ZERO =>
{
overrun_at(last, interval, at)
}
_ => 0,
}
}
/// After a reported stop's hooks read `thread`'s private queue
/// (`thread_holds`) and its process's shared one (`process_holds`): pop
/// the entry the stop took, re-arm its timer, and send the next entry
/// (4262 design §4.6 steps 2 and 3). A copy resumed blocked is requeued
/// by the kernel, so nothing pops. The read must agree with the model
/// (rev 9 A''): the identified queue's bit is clear, since the promotion
/// has not been sent yet, and the other queue's bit is set exactly when
/// its list or its discarded bit says a copy is there.
/// Returns the dequeue to pop (`pop_and_promote`), once 4351's record has
/// retired its bits.
pub(crate) fn finish_timer_signal_dequeue(
&mut self,
thread: DetTid,
signal: i32,
how: Consumption,
thread_holds: bool,
process_holds: bool,
) -> Option<PendingDequeue> {
let mut pending = self.pending_timer_dequeues.remove(&thread)?;
// A delivery resumed blocked requeues its copy (`ptrace_signal`'s
// `send_signal_locked`). After an early pop, while the joined send's
// copy is still pending in the identified queue, `legacy_queue` drops
// that requeue, and the kernel holds exactly the joined send, as the
// list does; natively the blocked signal would have stayed pending and
// coalesced the same way. The early-popped front is then retired below
// with the other unfinished dequeues (the Claude re-check of the
// in-flight-dequeue fix, R4). If another thread's stop already took
// the joined copy (a shared queue), the kernel queues the requeue,
// which the list cannot hold, so the run is refused (B1).
if pending.signal == signal
&& pending.early.is_some()
&& how == (Consumption::KeptResume { blocked: true })
&& !(if pending.queue == QueueId::Thread(thread) {
thread_holds
} else {
process_holds
})
{
refuse(format_args!(
"hermit: thread {thread}'s delivery of signal {signal} was resumed blocked after a send had taken the place of its front in {:?}, and another thread had already taken that send's copy (a delivery or an `rt_sigtimedwait`): the kernel queues the requeued copy, which the model of pending entries cannot hold, so the run is refused (https://github.com/rrnewton/hermit/issues/4262)",
pending.queue
));
}
if pending.signal != signal || how == (Consumption::KeptResume { blocked: true }) {
self.retire_unfinished_dequeue(pending);
return None;
}
// A delivery that never asked for its siginfo (it ended the thread
// group first) still re-arms its timer, at the committed time.
if let Some(captured) = pending.awaiting_info.take() {
let at = self.committed_time;
pending.reconcile = Some((captured.entry.timer, at, captured_overrun(&captured, at)));
}
// After an early pop, a send's copy is the identified queue's new
// front, physically there (`pop_in_flight_front`), unless another
// thread's delivery stop has since dequeued it and waits for its own
// turn (this pending dequeue is already removed, so any left for the
// same queue and signal is another's).
let identified_expected = pending.early.is_some()
&& self
.discarded_at_send
.lists
.is_listed(pending.queue, signal)
&& !self.pending_timer_dequeues.values().any(|other| {
// Another stop whose own front was popped early took a
// copy before this send joined, not the joined copy.
other.queue == pending.queue && other.signal == signal && other.early.is_none()
});
self.check_taken_queues(
thread,
pending.queue,
signal,
identified_expected,
thread_holds,
process_holds,
);
Some(pending)
}
/// The check of a dequeue of `signal` from `queue` by `thread` against
/// its queues read after it, before any promotion (rev 9 A''): the
/// identified queue no longer holds the signal, and the other one holds
/// it exactly when its list or its discarded bit says so. A
/// contradiction is a producer or a consumer the schedule does not see,
/// and refuses by name.
fn check_taken_queues(
&self,
thread: DetTid,
queue: QueueId,
signal: i32,
identified_expected: bool,
thread_holds: bool,
process_holds: bool,
) {
let process = self.sigchld_process(thread);
let (private, shared) = (QueueId::Thread(thread), QueueId::Process(process));
let (other, identified_holds, other_holds) = if queue == private {
(shared, thread_holds, process_holds)
} else {
(private, process_holds, thread_holds)
};
let other_expected = self.discarded_at_send.lists.is_listed(other, signal)
|| self.discarded_at_send.is_discarded(other, signal);
if identified_holds != identified_expected || other_holds != other_expected {
refuse(format_args!(
"hermit: thread {thread} took signal {signal} from {queue:?}, and afterwards that queue {} the signal and {other:?} {} it, where the model of its pending entries expects it {} in {queue:?} and {} in {other:?}: a {} the schedule does not see, so the run is refused (https://github.com/rrnewton/hermit/issues/4262)",
if identified_holds {
"still held"
} else {
"no longer held"
},
if other_holds { "held" } else { "did not hold" },
if identified_expected {
"held"
} else {
"absent"
},
if other_expected { "held" } else { "absent" },
// A copy the model lacks came from a producer it did not see;
// a copy it expected that is gone, from a consumer.
if (identified_holds && !identified_expected) || (other_holds && !other_expected) {
"producer"
} else {
"consumer"
},
));
}
}
/// A kept send of `signal` into `queue` found the kernel's queue without
/// the signal (`present` false) while its list still has a front: the
/// kernel dequeued that front at a delivery stop whose hooks have not run
/// yet (a `PendingDequeue` for it). Linux queues this send, so the front
/// is popped now, kept in the pending dequeue for the stop to finish, and
/// the send joins the empty list (A1).
///
/// Without this, a thread that `tgkill`s a signal again while another
/// thread's delivery of it waits for its turn left the new copy out of
/// the model, and the stop refused the run (cargo's jobserver helper
/// shutdown; the regression of
/// https://github.com/rrnewton/hermit/pull/4491). An entry behind the
/// in-flight front means Linux, whose bit stays set, drops this send
/// while the kernel kept it: no list can say that, so it is refused.
///
/// The joining send's `standing` (`note_send_listed`) is read from the
/// discarded bit, which still describes the in-flight copy until the
/// stop finishes: after an early pop of a `Proxy` front standing on a
/// discarded copy, the send joins as `Proxy` with that record's
/// `SI_TIMER` flag. A later delivery rewrites it from its stored bytes,
/// and an exec re-send merges into the kept copy, so the record the guest
/// sees is the send's own (the Claude review of the in-flight-dequeue
/// fix, F6).
pub(crate) fn pop_in_flight_front(&mut self, queue: QueueId, signal: i32, present: bool) {
if present || !self.discarded_at_send.lists.is_listed(queue, signal) {
return;
}
let Some((&thread, _)) = self.pending_timer_dequeues.iter().find(|(_, pending)| {
pending.queue == queue && pending.signal == signal && pending.early.is_none()
}) else {
return;
};
let Some(popped) = self.discarded_at_send.lists.pop(queue, signal) else {
return;
};
if popped.next.is_some() {
refuse(format_args!(
"hermit: a send of signal {signal} found {queue:?} without it while thread {thread}'s delivery of its front waited for its turn, and the front had an entry behind it: Linux drops that send, but the kernel queued it, which the model of pending entries cannot hold, so the run is refused (https://github.com/rrnewton/hermit/issues/4262)"
));
}
debug!(
"[dtid {}] signal {} in {:?}: the front a delivery took is popped early; a send joins the list.",
thread, signal, queue
);
if let Some(pending) = self.pending_timer_dequeues.get_mut(&thread) {
pending.early = Some(popped);
}
}
/// Thread `thread` exited with a dequeue pending: a front popped early
/// for it (`pop_in_flight_front`) is retired as its thread's entries are,
/// so a periodic timer that waited for its dequeue re-arms.
pub(crate) fn forget_pending_dequeue(&mut self, thread: DetTid) {
if let Some(unfinished) = self.pending_timer_dequeues.remove(&thread) {
self.retire_unfinished_dequeue(unfinished);
}
}
/// A pending dequeue dropped without finishing (its thread exited, a new
/// stop replaced it, its finish did not match it, or its delivery was
/// resumed blocked): a front it holds
/// after an early pop (`pop_in_flight_front`) no longer has an owner, so
/// it is retired as a dead thread's entries are, and a periodic timer
/// that waited for its dequeue re-arms instead of stopping (the Claude
/// and Codex reviews of the in-flight-dequeue fix, F5 and P2). Before an
/// early pop the front is still in its list, where a later dequeue or the
/// queue's retirement reconciles it.
fn retire_unfinished_dequeue(&mut self, unfinished: PendingDequeue) {
if let Some(popped) = unfinished.early {
self.note_private_entries_retired(vec![popped.entry]);
}
}
/// Pop `pending`'s front, reconcile its timer, and promote the next entry
/// with `receiver` the thread that took it.
pub(crate) fn pop_and_promote(&mut self, pending: PendingDequeue, receiver: DetTid) {
let Some(popped) = pending.early.or_else(|| {
self.discarded_at_send
.lists
.pop(pending.queue, pending.signal)
}) else {
return;
};
if let (Entry::Timer(entry), Some((timer, at, overrun))) = (popped.entry, pending.reconcile)
{
debug_assert_eq!(entry.timer, timer);
let id = SignalTimerId::Posix(entry.process, timer);
if entry.periodic_at_send
&& let Some(next) = self.blocked.timed_waiters.signal_timer_rearm_after(id, at)
{
self.posix_timer_overruns
.insert((entry.process, timer), overrun);
debug!(
"[dpid {}] POSIX timer {} delivered with overrun {}; re-armed at {}.",
entry.process, timer, overrun, next
);
}
}
debug_assert!(self.discarded_at_send.lists.invariants_hold());
if let Some(Entry::Timer(next)) = popped.next {
// At a delivery the kernel sets up the handler frame before the
// receiver can take anything else: its mask then decides the
// promotion's target (§4.5, P3-3).
let process = self.sigchld_process(receiver);
self.delivery_mask_override = match self.handler_masks.get(&(process, pending.signal)) {
Some(&(mask, nodefer)) if pending.delivery => {
let own = self.thread_signal_mask(receiver).unwrap_or(0);
let deferred = if nodefer {
0
} else {
kernel_signal_bit(pending.signal)
};
Some((receiver, own | mask | deferred))
}
_ => None,
};
self.promote(pending.queue, pending.signal, next, receiver);
self.delivery_mask_override = None;
}
}
/// Send the new front `next` of `queue`'s list for `signal` (promotion,
/// 4262 design §4.5): kept, as Linux queued it at its own expiry.
fn promote(&mut self, queue: QueueId, signal: i32, next: TimerEntry, receiver: DetTid) {
let Ok(sig) = Signal::try_from(signal) else {
return;
};
info!(
"[dtid {}] signal {} dequeued from {:?}; promoting POSIX timer {}'s entry.",
receiver, sig, queue, next.timer
);
let info = self.timer_signal_info(signal, &next, 0);
self.send_timer_record(queue, sig, receiver, info, SendFate::Kept);
}
/// Thread `thread` exited, taking its private lists with it
/// (`entries`, N9-5): a periodic timer that waited for the dequeue of one
/// of them re-arms now, so its next expiry finds the thread gone and is
/// dropped, as Linux drops it, with the timer still armed.
pub(crate) fn note_private_entries_retired(&mut self, entries: Vec<Entry>) {
let now = self.committed_time;
for entry in entries {
// Only an entry of the timer's current arming re-arms it: a
// `timer_settime` since the entry was queued started a newer
// generation, which waits for its own entry's dequeue (the Codex
// re-check of the in-flight-dequeue fix, P2-1).
if let Entry::Timer(entry) = entry
&& entry.periodic_at_send
&& self.timer_entry_valid(&entry)
{
self.blocked.timed_waiters.signal_timer_rearm_after(
SignalTimerId::Posix(entry.process, entry.timer),
now,
);
}
}
}
/// `timer_getoverrun` of `process`'s timer `timer`: `it_overrun_last`.
pub(crate) fn posix_timer_overrun(&self, process: DetPid, timer: i32) -> i32 {
self.posix_timer_overruns
.get(&(process, timer))
.copied()
.unwrap_or(0)
}
/// `timer_gettime`'s remaining time of `process`'s timer `timer` at `now`
/// (4262 design §5), or `None` where the caller's own answer stands
/// (record and replay, or a timer the scheduler does not know). An Active
/// timer past its deadline, whose pop waits for a turn boundary, reads
/// 1 ns (`common_timer_get` of an armed hrtimer); one
/// waiting for the dequeue of its entry reads the time to its next grid
/// point, a full interval on an exact hit (`timer_forward`); a popped
/// one-shot or a disarmed timer reads 0.
pub(crate) fn posix_timer_remaining(
&self,
process: DetPid,
timer: i32,
now: LogicalTime,
) -> Option<LogicalTime> {
// A timer the scheduler never registered (a real-time one in a
// permissive run) keeps the caller's own answer.
if !self.coalesces_alarms() || !self.posix_timer_live(process, timer) {
return None;
}
let id = SignalTimerId::Posix(process, timer);
let remaining = match self.blocked.timed_waiters.signal_timer_state(id) {
None => 0,
Some((deadline, _, AlarmPhase::Active)) => {
deadline.as_nanos().saturating_sub(now.as_nanos()).max(1)
}
Some((last, interval, AlarmPhase::Inactive { .. })) => {
grid_after(last, interval, now).as_nanos() - now.as_nanos()
}
};
Some(LogicalTime::from_nanos(remaining))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn at(ns: u64) -> LogicalTime {
LogicalTime::from_nanos(ns)
}
#[test]
fn the_overrun_counts_the_missed_periods() {
// Expired at 10 with interval 10; dequeued before the next period.
assert_eq!(overrun_at(at(10), at(10), at(15)), 0);
// An exact hit on the next grid point forwards past it.
assert_eq!(overrun_at(at(10), at(10), at(20)), 1);
// Five periods blocked: 4 missed.
assert_eq!(overrun_at(at(10), at(10), at(55)), 4);
assert_eq!(overrun_at(at(0), at(1), at(u64::MAX)), i32::MAX);
}
}