tickertape 0.5.1

A local, append-only event journal on memory-mapped segment files, with live cross-process readers and replay
Documentation
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
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
//! Memory maps and operating-system calls: the **only** module in this crate that contains `unsafe` code.
//!
//! Everything here is a thin, bounds-checked wrapper. The protocol reasoning lives in ADR 0003; each `unsafe`
//! block says which invariant it relies on and where that invariant is upheld.
//!
//! - [`MapRw`]: the writer's `PROT_READ | PROT_WRITE`, `MAP_SHARED` mapping. Commit words are stored with
//!   `Release` and loaded with `Acquire` through `AtomicU32::from_ptr` (the memory is writable, as `from_ptr`
//!   requires). Body bytes are written through `&mut [u8]` slices of exactly the uncommitted range.
//! - [`MapRo`]: the zero-copy reader's `PROT_READ`, `MAP_SHARED` mapping, used only on targets where
//!   `core::sync::atomic` documents 4- and 8-byte `Relaxed` loads as permitted on read-only memory
//!   ([`MAPPED_READS`]: x86-64 and aarch64). Commit words are loaded with `Relaxed`, followed by an `Acquire` fence.
//!   Record bodies are validated from `Relaxed` 4- and 8-byte atomic loads ([`SharedWords`], ADR 0027). Committed
//!   bytes are handed out only through an `unsafe fn`, whose contract is `Reader::open_mapped`'s.
//! - File-level calls: `flock`, preallocation, `fdatasync`/`fsync`/`F_FULLFSYNC`, `msync`, `pread`.

use std::fs::File;
use std::io;
use std::os::fd::AsRawFd;
use std::ptr::NonNull;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering, fence};
use std::time::Duration;

/// Checks that `[offset, offset + len)` lies inside a mapping of `map_len` bytes. Returns the range end.
fn checked_range(map_len: usize, offset: u64, len: u64) -> Option<usize> {
    let end = offset.checked_add(len)?;
    if end > map_len as u64 {
        return None;
    }
    usize::try_from(end).ok()
}

/// Checks that a commit word at `offset` is 8-aligned and inside a mapping of `map_len` bytes.
fn checked_word(map_len: usize, offset: u64) -> Option<usize> {
    if offset % 8 != 0 {
        return None;
    }
    checked_range(map_len, offset, 4)?;
    usize::try_from(offset).ok()
}

fn last_os_error() -> io::Error {
    io::Error::last_os_error()
}

/// Maps `len` bytes of `file` from offset 0 with the given protection, shared.
fn map(file: &File, len: usize, prot: libc::c_int) -> io::Result<NonNull<u8>> {
    if len == 0 {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "cannot map zero bytes",
        ));
    }
    // SAFETY: mmap with a null hint, a valid open file descriptor, offset 0 and a non-zero length has no memory-safety
    // preconditions; it either returns a fresh mapping that no Rust object aliases yet, or MAP_FAILED.
    let ptr = unsafe {
        libc::mmap(
            std::ptr::null_mut(),
            len,
            prot,
            libc::MAP_SHARED,
            file.as_raw_fd(),
            0,
        )
    };
    if ptr == libc::MAP_FAILED {
        return Err(last_os_error());
    }
    NonNull::new(ptr.cast::<u8>()).ok_or_else(|| io::Error::other("mmap returned null"))
}

/// Unmaps a mapping created by [`map`].
///
/// # Safety
///
/// `ptr` and `len` must describe a live mapping returned by [`map`], and no reference into it may outlive this call.
unsafe fn unmap(ptr: NonNull<u8>, len: usize) {
    // SAFETY: guaranteed by the caller. A failure can only mean invalid arguments, which the caller rules out.
    unsafe {
        libc::munmap(ptr.as_ptr().cast(), len);
    }
}

/// The system page size.
pub(crate) fn page_size() -> usize {
    // SAFETY: sysconf has no memory-safety preconditions.
    let n = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
    if n <= 0 { 4096 } else { n as usize }
}

/// `msync(MS_SYNC)` on the pages covering `[offset, offset + len)` of a mapping.
fn msync(ptr: NonNull<u8>, map_len: usize, offset: u64, len: u64) -> io::Result<()> {
    if len == 0 {
        return Ok(());
    }
    let end = checked_range(map_len, offset, len)
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "msync range out of bounds"))?;
    let page = page_size();
    let start = (offset as usize) / page * page;
    // SAFETY: `[start, end)` lies within the mapping (checked above; `start` is rounded down to a page boundary at or
    // after the mapping's page-aligned start). msync only flushes; it doesn't create references or change memory.
    let rc = unsafe { libc::msync(ptr.as_ptr().add(start).cast(), end - start, libc::MS_SYNC) };
    if rc != 0 {
        Err(last_os_error())
    } else {
        Ok(())
    }
}

/// The address range of a writer mapping, unmapped when its last owner (the [`MapRw`] or an [`Advice`]) is dropped.
#[derive(Debug)]
struct Region {
    ptr: NonNull<u8>,
    len: usize,
}

// SAFETY: a `Region` is only an address range plus the duty to unmap it once. It never dereferences `ptr`: data
// access goes through `MapRw`, whose borrows are tied to `&MapRw`/`&mut MapRw`, and `Advice` only passes the range to
// `madvise`. Sharing or moving the range between threads is therefore like sharing an integer.
unsafe impl Send for Region {}
// SAFETY: as above.
unsafe impl Sync for Region {}

impl Drop for Region {
    fn drop(&mut self) {
        // SAFETY: the mapping was created by `map` with this length. Every reference into it borrows the `MapRw` that
        // holds this region, and an `Advice` holds no references, so none can outlive the last owner's drop.
        unsafe { unmap(self.ptr, self.len) }
    }
}

/// The writer's read-write shared mapping of one segment file.
#[derive(Debug)]
pub(crate) struct MapRw {
    ptr: NonNull<u8>,
    len: usize,
    /// Keeps the mapping alive; shared only with [`Advice`] handles, which never access the bytes.
    region: Arc<Region>,
}

// SAFETY: `MapRw` is the only owner in this process that accesses the mapping's bytes (it is never cloned and hands out
// borrows tied to `&self`/`&mut self`; `Advice` handles never access the bytes), so moving it to another thread is like
// moving a `Vec<u8>`.
unsafe impl Send for MapRw {}

impl MapRw {
    /// Maps the first `len` bytes of `file` (opened read-write) for reading and writing.
    pub(crate) fn new(file: &File, len: usize) -> io::Result<MapRw> {
        let ptr = map(file, len, libc::PROT_READ | libc::PROT_WRITE)?;
        Ok(MapRw {
            ptr,
            len,
            region: Arc::new(Region { ptr, len }),
        })
    }

    /// A handle that can prefault this mapping from another thread and keeps it mapped while it lives (ADR 0020).
    pub(crate) fn advice(&self) -> Advice {
        Advice {
            region: Arc::clone(&self.region),
        }
    }

    /// The mapping's length.
    pub(crate) fn len(&self) -> usize {
        self.len
    }

    fn word(&self, offset: u64) -> Option<&AtomicU32> {
        let off = checked_word(self.len, offset)?;
        // SAFETY: `off` is 8-aligned (so 4-aligned, as AtomicU32 requires; the mapping itself is page-aligned) and
        // `[off, off + 4)` is inside the mapping, which is readable and writable for as long as `self` lives (the
        // returned reference borrows `self`). Other processes access commit words only atomically (ADR 0003), and this
        // module never creates a non-atomic reference that covers a commit word while other processes may load it.
        Some(unsafe { AtomicU32::from_ptr(self.ptr.as_ptr().add(off).cast::<u32>()) })
    }

    /// Loads the commit word at `offset` with `Acquire`. `None` if misaligned or out of bounds.
    pub(crate) fn commit_word(&self, offset: u64) -> Option<u32> {
        Some(self.word(offset)?.load(Ordering::Acquire))
    }

    /// Stores the commit word at `offset` with `Release`, publishing every byte written before it.
    pub(crate) fn store_commit_word(&self, offset: u64, value: u32) -> Option<()> {
        self.word(offset)?.store(value, Ordering::Release);
        Some(())
    }

    /// Mutable access to `[offset, offset + len)`.
    ///
    /// The writer only calls this for bytes that no reader reads: the body of a record before its commit word is
    /// stored, a seal's CRC before its marker, or the uncommitted tail during recovery (never a commit word that a
    /// reader may be loading). Committed bytes are never modified (ADR 0003), with one exception: recovery can zero
    /// records that storage damage made look uncommitted (an emptied commit word; `docs/crash-contract.md`, C11 (3)),
    /// as `Reader::open_mapped` documents.
    pub(crate) fn bytes_mut(&mut self, offset: u64, len: u64) -> Option<&mut [u8]> {
        let end = checked_range(self.len, offset, len)?;
        let start = offset as usize;
        // SAFETY: the range is inside the mapping (checked); `&mut self` guarantees no other reference into the mapping
        // exists in this process for the returned lifetime; other processes never write the file (single writer, held
        // by the lock) and readers don't read these bytes until a later release store makes them visible.
        Some(unsafe { std::slice::from_raw_parts_mut(self.ptr.as_ptr().add(start), end - start) })
    }

    /// Shared access to `[offset, offset + len)`, for the writer's own validation and copying.
    ///
    /// Sound because only the writer (this process, holding the lock) ever writes the file, and `&self` excludes
    /// concurrent writes through [`MapRw::bytes_mut`] for the returned lifetime. Commit words inside the range are
    /// not being stored concurrently either, for the same reason.
    pub(crate) fn bytes(&self, offset: u64, len: u64) -> Option<&[u8]> {
        let end = checked_range(self.len, offset, len)?;
        let start = offset as usize;
        // SAFETY: as described above: in bounds, and no concurrent writer to these bytes exists while `&self` is held.
        Some(unsafe { std::slice::from_raw_parts(self.ptr.as_ptr().add(start), end - start) })
    }

    /// `msync(MS_SYNC)` on the pages covering `[offset, offset + len)`.
    pub(crate) fn sync_range(&self, offset: u64, len: u64) -> io::Result<()> {
        msync(self.ptr, self.len, offset, len)
    }

    /// A handle that can `msync` ranges of this mapping from another thread while the writer keeps storing into it,
    /// and keeps the mapping alive while it lives (ADR 0038).
    pub(crate) fn flush_handle(&self) -> Flush {
        Flush {
            region: Arc::clone(&self.region),
        }
    }
}

/// Writes back ranges of a writer mapping from any thread (the background checkpoint, ADR 0038). Like [`Advice`], it
/// never reads or writes the mapped bytes, and it keeps the mapping alive while it exists.
///
/// Why `msync` on one thread while the writer stores into the same pages on another is sound: `msync` passes an
/// address range to the kernel and creates no reference into the mapping, so in Rust's terms this thread accesses no
/// memory at all, and the writer's `&mut` slices stay the only access from this process. What the kernel writes to the
/// file is whatever the pages hold when it copies them: every byte the writer stored before the checkpoint was
/// requested (ordered before the `msync` by the hand-over of the request between the threads), and, for bytes stored
/// during the call, old or new contents in any mixture. The checkpoint marker names only positions before the request,
/// so the bytes written during the call are never claimed durable; they are records not covered by a checkpoint
/// (`docs/crash-contract.md`, C8).
#[derive(Debug, Clone)]
pub(crate) struct Flush {
    region: Arc<Region>,
}

impl Flush {
    /// `msync(MS_SYNC)` on the pages covering `[offset, offset + len)` of the mapping.
    pub(crate) fn sync_range(&self, offset: u64, len: u64) -> io::Result<()> {
        msync(self.region.ptr, self.region.len, offset, len)
    }
}

/// Asks the kernel to fault in part of a writer mapping ahead of the writer (ADR 0020), from any thread. It never
/// reads or writes the mapped bytes, and it keeps the mapping alive while it exists.
#[derive(Debug, Clone)]
pub(crate) struct Advice {
    region: Arc<Region>,
}

impl Advice {
    /// The mapping's length.
    pub(crate) fn len(&self) -> u64 {
        self.region.len as u64
    }

    /// Prefaults the pages covering `[offset, offset + len)`, clamped to the mapping: `MADV_WILLNEED` on macOS,
    /// `MADV_POPULATE_WRITE` on Linux (an `InvalidInput` error before Linux 5.14; ADR 0025), nothing elsewhere. Contents
    /// are unchanged; on Linux the pages become dirty, so the kernel writes back their (zero) bytes.
    pub(crate) fn prefault(&self, offset: u64, len: u64) -> io::Result<()> {
        let map_len = self.region.len;
        let page = page_size();
        let start = usize::try_from(offset).unwrap_or(usize::MAX).min(map_len) / page * page;
        let end = usize::try_from(offset.saturating_add(len))
            .unwrap_or(usize::MAX)
            .min(map_len);
        if start >= end {
            return Ok(());
        }
        #[cfg(not(any(target_vendor = "apple", target_os = "linux")))]
        return Ok(());
        #[cfg(any(target_vendor = "apple", target_os = "linux"))]
        {
            #[cfg(target_vendor = "apple")]
            let advice = libc::MADV_WILLNEED;
            #[cfg(target_os = "linux")]
            let advice = libc::MADV_POPULATE_WRITE;
            let ptr = self.region.ptr.as_ptr();
            // SAFETY: `[start, end)` lies within the live mapping (clamped above; `start` is page-aligned, as is the
            // mapping), which `self.region` keeps mapped for the duration of the call. MADV_WILLNEED only reads pages
            // into the page cache. MADV_POPULATE_WRITE handles write faults for the range as a write would: it
            // populates page tables, marks the pages dirty and may allocate filesystem blocks, but performs no memory
            // store. Neither reads or writes the bytes from the program's point of view, so neither can conflict
            // with the writer's concurrent access through `&mut` slices.
            let rc = unsafe { libc::madvise(ptr.add(start).cast(), end - start, advice) };
            if rc != 0 {
                Err(last_os_error())
            } else {
                Ok(())
            }
        }
    }
}

/// Whether this target maps segments for reading (the zero-copy reader). Only x86-64 and aarch64: there
/// `core::sync::atomic` ("Atomic accesses to read-only memory") documents `Relaxed` loads of up to 8 bytes as
/// permitted on read-only memory, and they are plain single load instructions. On 32-bit targets the limit is 4 bytes
/// (an 8-byte atomic load on i686 without SSE is a locked compare-exchange, which faults on a read-only page), so
/// `Reader::open_mapped` reads with `pread` there instead (ADR 0027 → Supported targets).
pub(crate) const MAPPED_READS: bool = cfg!(any(target_arch = "x86_64", target_arch = "aarch64"));

/// A zero-copy reader's read-only shared mapping of one segment file.
///
/// Reads before validation go only through [`MapRo::commit_word`], [`MapRo::load_u32`] and [`MapRo::words`], all
/// `Relaxed` atomic loads through references that assert no immutability. What makes those loads sound on an intact
/// publication chain, and the cases in which they are not covered by Rust's memory model (commit words damaged on
/// storage), is set out in ADR 0027 → "Which loads can race".
#[derive(Debug)]
pub(crate) struct MapRo {
    ptr: NonNull<u8>,
    len: usize,
}

// SAFETY: as for `MapRw`: the mapping is owned exclusively and only borrowed through `&self`.
unsafe impl Send for MapRo {}

impl MapRo {
    /// Maps the first `len` bytes of `file` (which may be opened read-only) for reading. `Unsupported` on targets
    /// without [`MAPPED_READS`], where nothing may be loaded atomically from a read-only mapping.
    pub(crate) fn new(file: &File, len: usize) -> io::Result<MapRo> {
        if !MAPPED_READS {
            return Err(io::Error::new(
                io::ErrorKind::Unsupported,
                "read-only mappings are not used on this target",
            ));
        }
        let ptr = map(file, len, libc::PROT_READ)?;
        Ok(MapRo { ptr, len })
    }

    /// Loads the commit word at `offset`: a `Relaxed` load, then an `Acquire` fence if it is non-zero, so that later
    /// reads of the body see everything written before the writer's release store. `None` if misaligned or out of
    /// bounds.
    pub(crate) fn commit_word(&self, offset: u64) -> Option<u32> {
        let off = checked_word(self.len, offset)?;
        // SAFETY: aligned and in bounds (checked); the mapping lives as long as `self`. The reference is created by a
        // pointer cast, not `AtomicU32::from_ptr` (which requires writable memory), and is used only for a 4-byte
        // `Relaxed` load, which `core::sync::atomic` documents as permitted on read-only memory on the targets that
        // map segments for reading (`MAPPED_READS`; `new` refuses elsewhere). On an intact publication chain the
        // writer accesses commit words only with 4-byte atomic stores (ADR 0003), so this load has no data race (it
        // meets only matching 4-byte atomic stores) and is never mixed-size. A commit word damaged on storage breaks
        // that: if a published record's commit word reads as zero, recovery can zero that record and the records
        // after it in place under a live reader, and this load can then meet a writer's stores that are not 4-byte
        // atomics at this address (ADR 0027 → "Which loads can race").
        let word = unsafe { &*self.ptr.as_ptr().add(off).cast::<AtomicU32>() };
        let value = word.load(Ordering::Relaxed);
        if value != 0 {
            fence(Ordering::Acquire);
        }
        Some(value)
    }

    /// Loads the 4 bytes at `offset` (a multiple of 4) with one `Relaxed` atomic load, without creating any
    /// reference that outlives the load. The reader uses it for the CRC field at `P+4` of a record or seal whose
    /// non-zero commit word at `P` it has just observed. `None` if misaligned or out of bounds.
    pub(crate) fn load_u32(&self, offset: u64) -> Option<u32> {
        if offset % 4 != 0 {
            return None;
        }
        checked_range(self.len, offset, 4)?;
        // SAFETY: memory. `offset` is 4-aligned, as `AtomicU32` requires (the mapping is page-aligned), and
        // `[offset, offset + 4)` is inside the mapping (checked above), which stays mapped while `self` lives. The
        // temporary `&AtomicU32` comes from a pointer cast (`AtomicU32::from_ptr` requires writable memory), lives
        // only for this statement, and is used for one 4-byte `Relaxed` load: `core::sync::atomic` ("Atomic accesses
        // to read-only memory") permits exactly that on read-only memory on the targets that map segments for reading
        // (`MAPPED_READS`; `new` refuses elsewhere). `AtomicU32` is an `UnsafeCell`, so the reference asserts nothing
        // about the bytes staying unchanged.
        // Races. The reader's two uses load `[P+4, P+8)` after observing the commit word at `P`. On an intact
        // publication chain the writer stored those 4 bytes before its `Release` store of that word, which the
        // reader's `Acquire` fence synchronises with, and never stores to them again, so this load has no data race.
        // A commit word damaged on storage breaks that: a writer can then be storing to these bytes (recovery zeroing
        // a published record whose commit word reads as zero, in place, under a live reader), and the load races
        // with those stores (ADR 0027 → "Which loads can race").
        let word = unsafe { &*self.ptr.as_ptr().add(offset as usize).cast::<AtomicU32>() };
        Some(word.load(Ordering::Relaxed))
    }

    /// The `count` 8-byte words starting at `offset` (a multiple of 8), readable only through `Relaxed` atomic loads
    /// (ADR 0027). The reader asks for the words of `[P+8, P+align8(len))` of a record whose commit word at `P` holds
    /// `len`, and validates the record from them before [`MapRo::committed_bytes`] may be used on it. `None` if
    /// misaligned or out of bounds.
    pub(crate) fn words(&self, offset: u64, count: u64) -> Option<SharedWords<'_>> {
        if offset % 8 != 0 {
            return None;
        }
        let end = checked_range(self.len, offset, count.checked_mul(8)?)?;
        let start = offset as usize;
        // SAFETY: memory. `start` is 8-aligned, as `AtomicU64` requires (the mapping is page-aligned), and
        // `[start, end)` is inside the mapping (checked above, with the multiplication overflow-checked), which stays
        // mapped for the returned lifetime because it borrows `self`. The `&[AtomicU64]` is a reference, but one to
        // `UnsafeCell`s: it asserts nothing about the bytes staying unchanged, unlike a `&[u8]`, which is only formed
        // after validation (`committed_bytes`). The memory is read-only, so the slice may only be used for 8-byte
        // `Relaxed` loads, which `core::sync::atomic` ("Atomic accesses to read-only memory") permits on read-only
        // memory on the targets that map segments for reading (`MAPPED_READS`; `new` refuses elsewhere).
        // `SharedWords` keeps the slice private and offers nothing else.
        // Races. For a record published by the protocol, the writer stored every byte of `[P+8, P+align8(len))`
        // (padding was zero beforehand) before its `Release` store of the commit word, which the reader's `Acquire`
        // fence synchronises with, and never stores to them again; the words end at the next slot's commit word and
        // never cover another record's commit word. So the loads race with no store and overlap no atomic access of
        // another size. If the length in the commit word is damaged, the words can reach past the writer's current
        // slot, where a live writer is storing body bytes (non-atomic) and the next commit word (a 4-byte atomic).
        // That is a data race, and a mixed-size access, in Rust's memory model when the writer is in this process,
        // before any CRC runs, and outside the model when it is another process. A zeroed commit word can let
        // recovery zero published records in place under a live reader, with the same result (when: crash contract
        // C11 (3)). The code then assumes, without a guarantee, that each load is one aligned 8-byte load instruction
        // on these targets, which cannot fault inside the mapping and returns some mixture of old and new bytes; that
        // the compiler does not split, repeat or invent an atomic load; and that, since no reference asserting
        // immutability exists, the CRC then rejects the mixed frame. The copying reader before ADR 0027 loaded the same bytes the same way. A known
        // limitation: ADR 0027 → "Which loads can race".
        let words = unsafe {
            std::slice::from_raw_parts(
                self.ptr.as_ptr().add(start).cast::<AtomicU64>(),
                (end - start) / 8,
            )
        };
        Some(SharedWords { words })
    }

    /// Shared access to `[offset, offset + len)`. `None` if out of bounds.
    ///
    /// # Safety
    ///
    /// The bytes must belong to a committed record that has already been validated (length, CRC, sequence, flags)
    /// from `Relaxed` atomic loads ([`MapRo::load_u32`], [`MapRo::words`]) made after observing its non-zero commit
    /// word, and no process may modify them while the returned slice lives. This is `Reader::open_mapped`'s safety
    /// contract; on an intact publication chain the tickertape writer never modifies committed bytes. Validating
    /// first means a damaged length is rejected by the CRC before a slice can cover bytes the writer is still
    /// appending to, under the assumption about racing loads in ADR 0027 → "Which loads can race".
    pub(crate) unsafe fn committed_bytes(&self, offset: u64, len: u64) -> Option<&[u8]> {
        let end = checked_range(self.len, offset, len)?;
        let start = offset as usize;
        // SAFETY: memory: in bounds (checked) and readable for `self`'s lifetime; `u8` has no alignment or validity
        // requirement. Unlike the atomic references used during validation, this `&[u8]` asserts that the bytes do
        // not change while it lives, and the reader reads them with ordinary loads. That holds by the caller's
        // contract on an intact publication chain: the frame is then the one the writer published with its
        // `Release` store (which happens before these reads, through the reader's `Acquire` fence), and nobody
        // modifies committed bytes afterwards. Passing validation does not prove the chain intact: ADR 0027 →
        // "Which loads can race" describes the two cases after storage damage in which this does not hold (an
        // enlarged length, and recovery zeroing published records in place after a commit word was emptied).
        Some(unsafe { std::slice::from_raw_parts(self.ptr.as_ptr().add(start), end - start) })
    }
}

impl Drop for MapRo {
    fn drop(&mut self) {
        // SAFETY: created by `map` with this length; every reference into it borrows `self`.
        unsafe { unmap(self.ptr, self.len) }
    }
}

/// A run of 8-byte words that may live in a read-only shared mapping, readable only through 8-byte `Relaxed` atomic
/// loads (ADR 0027). It never exposes a reference to the words, and each load is one atomic load of one word. Over
/// a published record no store races with these loads; over a frame whose length is damaged they may overlap bytes
/// a live writer is storing (see [`MapRo::words`] and ADR 0027 → "Which loads can race"), and validation then rejects
/// the mixture of old and new bytes they return.
///
/// Built over a mapping by [`MapRo::words`], or over ordinary memory by [`SharedWords::new`] (tests and fuzzing, so
/// that the validation code also runs under Miri). Words are little-endian like everything on disk (the crate
/// refuses big-endian targets), so word `i` holds bytes `[8i, 8i + 8)` of the run.
#[derive(Debug, Clone, Copy)]
pub(crate) struct SharedWords<'a> {
    /// Private: over a read-only mapping only `Relaxed` loads are allowed, which is all this type performs.
    words: &'a [AtomicU64],
}

impl<'a> SharedWords<'a> {
    /// Words in ordinary (writable) memory, where any atomic access is allowed.
    #[cfg_attr(not(any(test, fuzzing)), allow(dead_code))]
    pub(crate) fn new(words: &'a [AtomicU64]) -> SharedWords<'a> {
        SharedWords { words }
    }

    /// Number of words.
    #[inline]
    pub(crate) fn len(self) -> usize {
        self.words.len()
    }

    /// Word `i`, or `None` past the end.
    #[inline]
    pub(crate) fn get(self, i: usize) -> Option<u64> {
        Some(self.words.get(i)?.load(Ordering::Relaxed))
    }

    /// The first `mid` words and the rest, or `None` if `mid > len`.
    #[inline]
    pub(crate) fn split_at_checked(self, mid: usize) -> Option<(SharedWords<'a>, SharedWords<'a>)> {
        let (a, b) = self.words.split_at_checked(mid)?;
        Some((SharedWords { words: a }, SharedWords { words: b }))
    }

    /// Each word in order, each loaded exactly once as the iterator reaches it.
    #[inline]
    pub(crate) fn iter(self) -> impl Iterator<Item = u64> + 'a {
        self.words.iter().map(|w| w.load(Ordering::Relaxed))
    }

    /// Consecutive runs of exactly `n` words (`n > 0`), and the shorter run left over at the end.
    #[inline]
    pub(crate) fn chunks_exact(
        self,
        n: usize,
    ) -> (impl Iterator<Item = SharedWords<'a>>, SharedWords<'a>) {
        let chunks = self.words.chunks_exact(n);
        let rest = SharedWords {
            words: chunks.remainder(),
        };
        (chunks.map(|words| SharedWords { words }), rest)
    }
}

/// Size of the shared notify region (ADRs 0017 and 0021).
const NOTIFY_REGION_LEN: usize = 4096;
const NOTIFY_EVENT: u64 = 0;
const NOTIFY_WAITERS: u64 = 64;
const NOTIFY_WRITER_FLAG: u64 = 128;
const NOTIFY_NONCE_LO: u64 = 192;
const NOTIFY_NONCE_HI: u64 = 200;
/// Length of a macOS shared-memory object name, `/tickertape.` plus 16 hex digits.
pub(crate) const NOTIFY_NAME_LEN: usize = 28;

/// Where a writer's notify region lives (ADR 0021), as recorded in the journal's `notify` file.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum NotifyLocation {
    /// Linux: a sealed memfd, reachable as `/proc/<pid>/fd/<fd>` while the writer runs.
    Memfd { pid: u32, fd: i32 },
    /// macOS: a POSIX shared-memory object.
    Shm { name: [u8; NOTIFY_NAME_LEN] },
}

/// How a wait on the notify region ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum WaitOutcome {
    /// Woken, timed out, interrupted, or the counter had already changed: the caller re-checks.
    Returned,
    /// The platform call is unavailable or failed for good (for example blocked by a seccomp policy): stop waiting
    /// on the region and poll instead.
    Unsupported,
}

/// The wake-up words (ADR 0017) in a 4,096-byte shared region that the kernel won't let anyone shrink (ADR 0021):
/// an event counter the writer increments after each publication, a count of readers blocked on it, a flag saying
/// whether the attached writer maintains the counter, and a nonce that ties the region to the journal's record.
/// Because the backing can't shrink, no access to the mapping can raise `SIGBUS`, whatever other processes do. Its
/// contents never affect correctness, only latency: every wait has a timeout.
#[derive(Debug)]
pub(crate) struct Notify {
    map: MapRw,
    /// Set for the writer's own region: cleared and removed again when dropped.
    owner: Option<Owner>,
}

#[derive(Debug)]
struct Owner {
    /// Only held: on Linux it keeps the memfd reachable through `/proc/<pid>/fd/<fd>`.
    #[allow(dead_code)]
    file: File,
    /// macOS: the object's name, unlinked on drop.
    #[cfg_attr(not(target_vendor = "apple"), allow(dead_code))]
    name: Option<[u8; NOTIFY_NAME_LEN]>,
}

impl Notify {
    /// Writer: creates a fresh region tagged with `nonce`, sets the writer flag, and returns it with its location.
    pub(crate) fn create(nonce: u64) -> io::Result<(Notify, NotifyLocation)> {
        let (file, location, name) = create_region(nonce)?;
        let mapped = (|| {
            file.set_len(NOTIFY_REGION_LEN as u64)?;
            // Linux: seal only after sizing (F_SEAL_GROW would forbid the `set_len` above).
            #[cfg(target_os = "linux")]
            seal(&file)?;
            MapRw::new(&file, NOTIFY_REGION_LEN)
        })();
        let map = match mapped {
            Ok(map) => map,
            Err(e) => {
                // No record names the region yet, so nobody else could remove it later.
                if let Some(name) = &name {
                    unlink_region(name);
                }
                return Err(e);
            }
        };
        let notify = Notify {
            map,
            owner: Some(Owner { file, name }),
        };
        notify
            .word(NOTIFY_NONCE_LO)
            .store(nonce as u32, Ordering::SeqCst);
        notify
            .word(NOTIFY_NONCE_HI)
            .store((nonce >> 32) as u32, Ordering::SeqCst);
        notify.word(NOTIFY_WRITER_FLAG).store(1, Ordering::SeqCst);
        Ok((notify, location))
    }

    /// Reader: maps the region at `location` if it can't shrink, is at least 4,096 bytes and carries `nonce`.
    pub(crate) fn attach(location: &NotifyLocation, nonce: u64) -> io::Result<Notify> {
        let file = open_region(location)?;
        if file.metadata()?.len() < NOTIFY_REGION_LEN as u64 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "notify region too short",
            ));
        }
        let notify = Notify {
            map: MapRw::new(&file, NOTIFY_REGION_LEN)?,
            owner: None,
        };
        if notify.nonce() != nonce {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "notify region belongs to another writer",
            ));
        }
        Ok(notify)
    }

    fn word(&self, offset: u64) -> &AtomicU32 {
        // The offsets are constants inside the 4,096-byte mapping and 8-aligned, so `word` never fails.
        self.map
            .word(offset)
            .unwrap_or_else(|| unreachable!("notify offsets are in bounds"))
    }

    fn nonce(&self) -> u64 {
        u64::from(self.word(NOTIFY_NONCE_LO).load(Ordering::SeqCst))
            | u64::from(self.word(NOTIFY_NONCE_HI).load(Ordering::SeqCst)) << 32
    }

    /// Writer: a handle that publishes on this region from another thread (the background checkpoint, ADR 0038). It
    /// keeps the region mapped while it lives; clearing the writer flag stays with this `Notify`'s drop.
    pub(crate) fn publisher(&self) -> NotifyPublisher {
        NotifyPublisher {
            region: Arc::clone(&self.map.region),
        }
    }

    /// Reader: whether the writer that created the region still maintains the counter.
    pub(crate) fn writer_notifies(&self) -> bool {
        self.word(NOTIFY_WRITER_FLAG).load(Ordering::SeqCst) != 0
    }

    /// Writer, after publishing a record, seal or checkpoint: bump the event counter and wake blocked readers if
    /// any. Sequentially consistent, pairing with [`Notify::begin_wait`] (event-count protocol, ADR 0017).
    pub(crate) fn publish(&self) {
        let event = self.word(NOTIFY_EVENT);
        event.fetch_add(1, Ordering::SeqCst);
        if self.word(NOTIFY_WAITERS).load(Ordering::SeqCst) != 0 {
            wake_all(event);
        }
    }

    /// Reader, before its final check: register as a waiter and return the current event count.
    pub(crate) fn begin_wait(&self) -> u32 {
        self.word(NOTIFY_WAITERS).fetch_add(1, Ordering::SeqCst);
        self.word(NOTIFY_EVENT).load(Ordering::SeqCst)
    }

    /// Reader: block until the event count differs from `seen`, a wake-up arrives, or `timeout` passes.
    pub(crate) fn wait(&self, seen: u32, timeout: Duration) -> WaitOutcome {
        #[cfg(test)]
        {
            test_hooks::WAITS.fetch_add(1, Ordering::SeqCst);
            if test_hooks::FORCE_UNSUPPORTED.load(Ordering::SeqCst) {
                return WaitOutcome::Unsupported;
            }
        }
        wait_on(self.word(NOTIFY_EVENT), seen, timeout)
    }

    /// Reader: unregister as a waiter (never below zero, in case the count was reset).
    pub(crate) fn end_wait(&self) {
        let waiters = self.word(NOTIFY_WAITERS);
        let mut current = waiters.load(Ordering::SeqCst);
        while current != 0 {
            match waiters.compare_exchange_weak(
                current,
                current - 1,
                Ordering::SeqCst,
                Ordering::SeqCst,
            ) {
                Ok(_) => break,
                Err(actual) => current = actual,
            }
        }
    }
}

/// Publishes on the writer's wake-up region from another thread ([`Notify::publisher`]): the same event-count step as
/// [`Notify::publish`], so the writer's own handle, and its appends, are unchanged.
#[derive(Debug, Clone)]
pub(crate) struct NotifyPublisher {
    region: Arc<Region>,
}

impl NotifyPublisher {
    fn word(&self, offset: u64) -> &AtomicU32 {
        let off = checked_word(self.region.len, offset)
            .unwrap_or_else(|| unreachable!("notify offsets are in bounds"));
        // SAFETY: as in `MapRw::word`: `off` is 8-aligned and `[off, off + 4)` lies inside the region, which stays mapped
        // and writable while `self.region` lives (the returned reference borrows `self`). The region's words are only
        // ever accessed atomically, by this process (`Notify`, this handle) and by readers in others; nothing creates a
        // non-atomic reference into a notify region.
        unsafe { AtomicU32::from_ptr(self.region.ptr.as_ptr().add(off).cast::<u32>()) }
    }

    /// Bumps the event counter and wakes blocked readers if any, as [`Notify::publish`] does.
    pub(crate) fn publish(&self) {
        let event = self.word(NOTIFY_EVENT);
        event.fetch_add(1, Ordering::SeqCst);
        if self.word(NOTIFY_WAITERS).load(Ordering::SeqCst) != 0 {
            wake_all(event);
        }
    }

    /// The event counter, for tests that check when a wake-up was published.
    #[cfg(test)]
    pub(crate) fn event(&self) -> u32 {
        self.word(NOTIFY_EVENT).load(Ordering::SeqCst)
    }
}

impl Notify {
    /// A copy inherited across `fork`: closes this process's descriptor and mapping without clearing the writer flag,
    /// waking readers or removing the region, which still belong to the parent.
    pub(crate) fn release_after_fork(mut self) {
        self.owner = None;
    }
}

impl Drop for Notify {
    fn drop(&mut self) {
        let Some(owner) = &self.owner else { return };
        // Tell waiting readers that nobody maintains the counter any more, and wake them so they notice.
        self.word(NOTIFY_WRITER_FLAG).store(0, Ordering::SeqCst);
        self.publish();
        if let Some(name) = &owner.name {
            unlink_region(name);
        }
    }
}

/// Test-only instrumentation of [`Notify::wait`].
#[cfg(test)]
pub(crate) mod test_hooks {
    use std::sync::Mutex;
    use std::sync::atomic::{AtomicBool, AtomicU64};

    /// Calls to `Notify::wait`.
    pub(crate) static WAITS: AtomicU64 = AtomicU64::new(0);
    /// Makes every wait report `WaitOutcome::Unsupported`.
    pub(crate) static FORCE_UNSUPPORTED: AtomicBool = AtomicBool::new(false);
    /// Serialises the tests that use these hooks.
    pub(crate) static LOCK: Mutex<()> = Mutex::new(());
}

/// Removes a macOS shared-memory name left by an earlier writer of the journal (best effort; nothing elsewhere).
pub(crate) fn unlink_stale_region(location: &NotifyLocation) {
    if let NotifyLocation::Shm { name } = location {
        unlink_region(name);
    }
}

#[cfg(target_os = "linux")]
fn create_region(_nonce: u64) -> io::Result<(File, NotifyLocation, Option<[u8; NOTIFY_NAME_LEN]>)> {
    use std::os::fd::FromRawFd;
    // SAFETY: memfd_create with a NUL-terminated name and valid flags has no memory-safety preconditions; it returns
    // a new descriptor or -1.
    let fd = unsafe {
        libc::memfd_create(
            c"tickertape-notify".as_ptr(),
            libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING,
        )
    };
    if fd < 0 {
        return Err(last_os_error());
    }
    // SAFETY: `fd` is a freshly created descriptor that nothing else owns.
    let file = unsafe { File::from_raw_fd(fd) };
    Ok((
        file,
        NotifyLocation::Memfd {
            pid: std::process::id(),
            fd,
        },
        None,
    ))
}

/// Seals the memfd so that nobody can shrink, grow or unseal it (ADR 0021).
#[cfg(target_os = "linux")]
fn seal(file: &File) -> io::Result<()> {
    let seals = libc::F_SEAL_SHRINK | libc::F_SEAL_GROW | libc::F_SEAL_SEAL;
    // SAFETY: F_ADD_SEALS takes an integer argument and has no memory-safety preconditions.
    if unsafe { libc::fcntl(file.as_raw_fd(), libc::F_ADD_SEALS, seals) } != 0 {
        return Err(last_os_error());
    }
    Ok(())
}

#[cfg(target_os = "linux")]
fn open_region(location: &NotifyLocation) -> io::Result<File> {
    let NotifyLocation::Memfd { pid, fd } = location else {
        return Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "notify region of another platform",
        ));
    };
    let file = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .open(format!("/proc/{pid}/fd/{fd}"))?;
    // SAFETY: F_GET_SEALS takes no argument and has no memory-safety preconditions.
    let seals = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GET_SEALS) };
    if seals < 0 || seals & libc::F_SEAL_SHRINK == 0 {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "notify region can shrink",
        ));
    }
    Ok(file)
}

#[cfg(target_os = "linux")]
fn unlink_region(_name: &[u8; NOTIFY_NAME_LEN]) {}

/// A NUL-terminated copy of a shared-memory name.
#[cfg(target_vendor = "apple")]
fn c_name(name: &[u8; NOTIFY_NAME_LEN]) -> io::Result<std::ffi::CString> {
    std::ffi::CString::new(
        name.iter()
            .copied()
            .take_while(|&b| b != 0)
            .collect::<Vec<u8>>(),
    )
    .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "bad notify region name"))
}

#[cfg(target_vendor = "apple")]
fn create_region(nonce: u64) -> io::Result<(File, NotifyLocation, Option<[u8; NOTIFY_NAME_LEN]>)> {
    use std::os::fd::FromRawFd;
    let mut name = [0u8; NOTIFY_NAME_LEN];
    name.copy_from_slice(format!("/tickertape.{nonce:016x}").as_bytes());
    let c = c_name(&name)?;
    // SAFETY: shm_open with a NUL-terminated name, flags and a mode (passed as the promoted C `unsigned int` the
    // variadic signature expects) has no memory-safety preconditions; it returns a new descriptor or -1. (macOS
    // rejects O_CLOEXEC here; `set_cloexec` sets it afterwards.)
    let fd = unsafe {
        libc::shm_open(
            c.as_ptr(),
            libc::O_RDWR | libc::O_CREAT | libc::O_EXCL,
            0o600 as libc::c_uint,
        )
    };
    if fd < 0 {
        return Err(last_os_error());
    }
    // SAFETY: `fd` is a freshly created descriptor that nothing else owns.
    let file = unsafe { File::from_raw_fd(fd) };
    if let Err(e) = set_cloexec(&file) {
        unlink_region(&name);
        return Err(e);
    }
    Ok((file, NotifyLocation::Shm { name }, Some(name)))
}

#[cfg(target_vendor = "apple")]
fn open_region(location: &NotifyLocation) -> io::Result<File> {
    use std::os::fd::FromRawFd;
    let NotifyLocation::Shm { name } = location else {
        return Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "notify region of another platform",
        ));
    };
    if !name.starts_with(b"/tickertape.") {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "bad notify region name",
        ));
    }
    let c = c_name(name)?;
    // SAFETY: as in `create_region`; without O_CREAT the mode is ignored.
    let fd = unsafe { libc::shm_open(c.as_ptr(), libc::O_RDWR, 0 as libc::c_uint) };
    if fd < 0 {
        return Err(last_os_error());
    }
    // SAFETY: `fd` is a freshly opened descriptor that nothing else owns. Once sized, a POSIX shared-memory object
    // can't be resized on macOS (`ftruncate` fails with EINVAL; `notify_region_cannot_shrink` checks this), so the
    // size checked by the caller is permanent.
    let file = unsafe { File::from_raw_fd(fd) };
    set_cloexec(&file)?;
    Ok(file)
}

/// Sets `FD_CLOEXEC`, so child processes don't inherit the descriptor.
#[cfg(target_vendor = "apple")]
fn set_cloexec(file: &File) -> io::Result<()> {
    // SAFETY: F_SETFD with an integer flag on a valid descriptor has no memory-safety preconditions.
    if unsafe { libc::fcntl(file.as_raw_fd(), libc::F_SETFD, libc::FD_CLOEXEC) } != 0 {
        return Err(last_os_error());
    }
    Ok(())
}

#[cfg(target_vendor = "apple")]
fn unlink_region(name: &[u8; NOTIFY_NAME_LEN]) {
    if !name.starts_with(b"/tickertape.") {
        return;
    }
    if let Ok(c) = c_name(name) {
        // SAFETY: shm_unlink with a NUL-terminated name has no memory-safety preconditions; existing mappings stay
        // valid.
        unsafe { libc::shm_unlink(c.as_ptr()) };
    }
}

#[cfg(not(any(target_os = "linux", target_vendor = "apple")))]
fn create_region(_nonce: u64) -> io::Result<(File, NotifyLocation, Option<[u8; NOTIFY_NAME_LEN]>)> {
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "no notify region on this platform",
    ))
}

#[cfg(not(any(target_os = "linux", target_vendor = "apple")))]
fn open_region(_location: &NotifyLocation) -> io::Result<File> {
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "no notify region on this platform",
    ))
}

#[cfg(not(any(target_os = "linux", target_vendor = "apple")))]
fn unlink_region(_name: &[u8; NOTIFY_NAME_LEN]) {}

/// Blocks while `word == expected`, for at most `timeout` (spurious returns are fine; callers re-check).
#[cfg(target_os = "linux")]
fn wait_on(word: &AtomicU32, expected: u32, timeout: Duration) -> WaitOutcome {
    let ts = libc::timespec {
        tv_sec: libc::time_t::try_from(timeout.as_secs()).unwrap_or(libc::time_t::MAX),
        tv_nsec: timeout.subsec_nanos() as libc::c_long,
    };
    // SAFETY: FUTEX_WAIT (shared, i.e. without FUTEX_PRIVATE_FLAG, because the word lives in a MAP_SHARED mapping used
    // by several processes) reads the 4-byte aligned word at `word`'s address, which stays mapped for the duration of
    // the call because `word` borrows the mapping; `ts` lives on our stack. The kernel only compares and sleeps; it
    // never writes the word.
    let rc = unsafe {
        libc::syscall(
            libc::SYS_futex,
            word.as_ptr(),
            libc::FUTEX_WAIT,
            expected,
            &ts as *const libc::timespec,
            std::ptr::null::<u32>(),
            0u32,
        )
    };
    if rc == 0 {
        return WaitOutcome::Returned;
    }
    match io::Error::last_os_error().raw_os_error() {
        Some(libc::EAGAIN | libc::EINTR | libc::ETIMEDOUT) => WaitOutcome::Returned,
        _ => WaitOutcome::Unsupported,
    }
}

/// Wakes every thread blocked in [`wait_on`] on `word`, in any process.
#[cfg(target_os = "linux")]
fn wake_all(word: &AtomicU32) {
    // SAFETY: FUTEX_WAKE only uses the address as a key (shared futex, see `wait_on`); `word` is mapped while borrowed.
    unsafe {
        libc::syscall(
            libc::SYS_futex,
            word.as_ptr(),
            libc::FUTEX_WAKE,
            i32::MAX,
            std::ptr::null::<libc::timespec>(),
            std::ptr::null::<u32>(),
            0u32,
        );
    }
}

/// macOS 14.4+ `os_sync_wait_on_address_with_timeout` / `os_sync_wake_by_address_all`, looked up at run time so that
/// the library still runs (polling) on older systems.
#[cfg(target_vendor = "apple")]
mod os_sync {
    use std::sync::OnceLock;

    pub(super) type WaitFn =
        unsafe extern "C" fn(*mut libc::c_void, u64, libc::size_t, u32, u32, u64) -> libc::c_int;
    pub(super) type WakeFn =
        unsafe extern "C" fn(*mut libc::c_void, libc::size_t, u32) -> libc::c_int;
    /// `OS_SYNC_WAIT_ON_ADDRESS_SHARED` and `OS_SYNC_WAKE_BY_ADDRESS_SHARED` (`<os/os_sync_wait_on_address.h>`).
    pub(super) const SHARED: u32 = 0x1;
    /// `OS_CLOCK_MACH_ABSOLUTE_TIME` (`<os/clock.h>`).
    pub(super) const CLOCK_MACH_ABSOLUTE_TIME: u32 = 32;

    pub(super) fn functions() -> Option<(WaitFn, WakeFn)> {
        static FUNCTIONS: OnceLock<Option<(WaitFn, WakeFn)>> = OnceLock::new();
        *FUNCTIONS.get_or_init(|| {
            // SAFETY: dlsym with RTLD_DEFAULT and NUL-terminated names has no preconditions; a null result means the
            // symbol doesn't exist (macOS before 14.4).
            let wait = unsafe {
                libc::dlsym(
                    libc::RTLD_DEFAULT,
                    c"os_sync_wait_on_address_with_timeout".as_ptr(),
                )
            };
            // SAFETY: as above.
            let wake =
                unsafe { libc::dlsym(libc::RTLD_DEFAULT, c"os_sync_wake_by_address_all".as_ptr()) };
            if wait.is_null() || wake.is_null() {
                return None;
            }
            // SAFETY: the symbols have exactly these C signatures in the macOS SDK header named above.
            Some(unsafe {
                (
                    std::mem::transmute::<*mut libc::c_void, WaitFn>(wait),
                    std::mem::transmute::<*mut libc::c_void, WakeFn>(wake),
                )
            })
        })
    }
}

#[cfg(target_vendor = "apple")]
fn wait_on(word: &AtomicU32, expected: u32, timeout: Duration) -> WaitOutcome {
    let Some((wait, _)) = os_sync::functions() else {
        return WaitOutcome::Unsupported;
    };
    let ns = u64::try_from(timeout.as_nanos()).unwrap_or(u64::MAX).max(1);
    // SAFETY: the address is the 4-byte aligned word, mapped while `word` is borrowed; size 4 matches; the shared flag
    // matches the wake side; the kernel only compares the value and sleeps.
    let rc = unsafe {
        wait(
            word.as_ptr().cast(),
            u64::from(expected),
            4,
            os_sync::SHARED,
            os_sync::CLOCK_MACH_ABSOLUTE_TIME,
            ns,
        )
    };
    if rc >= 0 {
        return WaitOutcome::Returned;
    }
    match io::Error::last_os_error().raw_os_error() {
        Some(libc::ETIMEDOUT | libc::EINTR) => WaitOutcome::Returned,
        _ => WaitOutcome::Unsupported,
    }
}

#[cfg(target_vendor = "apple")]
fn wake_all(word: &AtomicU32) {
    if let Some((_, wake)) = os_sync::functions() {
        // SAFETY: the address is only used as a key; size and flags match `wait_on`.
        unsafe {
            wake(word.as_ptr().cast(), 4, os_sync::SHARED);
        }
    }
}

#[cfg(not(any(target_os = "linux", target_vendor = "apple")))]
fn wait_on(_word: &AtomicU32, _expected: u32, _timeout: Duration) -> WaitOutcome {
    WaitOutcome::Unsupported
}

#[cfg(not(any(target_os = "linux", target_vendor = "apple")))]
fn wake_all(_word: &AtomicU32) {}

/// Tries to take an exclusive `flock` without blocking. `Ok(false)` if another process holds it.
pub(crate) fn try_lock_exclusive(file: &File) -> io::Result<bool> {
    // SAFETY: flock on a valid descriptor has no memory-safety preconditions.
    let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
    if rc == 0 {
        return Ok(true);
    }
    let err = last_os_error();
    if err.raw_os_error() == Some(libc::EWOULDBLOCK) {
        Ok(false)
    } else {
        Err(err)
    }
}

/// Releases the `flock` held through `file`'s open file description.
///
/// The lock belongs to the description, not the descriptor: closing the descriptor releases it only once every copy
/// is closed, and a child forked by any thread holds a copy until it calls `exec` or exits. Unlocking releases it at
/// once, for every process sharing the description, so only the process that took the lock may call this.
pub(crate) fn unlock(file: &File) -> io::Result<()> {
    // SAFETY: flock on a valid descriptor has no memory-safety preconditions.
    let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_UN) };
    if rc == 0 {
        Ok(())
    } else {
        Err(last_os_error())
    }
}

/// Test helper: a forked child that has not called `exec`, holding copies of all of this process's descriptors.
#[cfg(test)]
pub(crate) mod forked {
    use std::fs::File;
    use std::io::{self, Write};
    use std::os::unix::io::{FromRawFd, RawFd};
    use std::sync::Mutex;
    use std::time::{Duration, Instant};

    /// Held by tests while their forked child exists, and by tests that rely on closing a descriptor to release a
    /// lock (the child holds a copy of every descriptor this process had at the fork).
    pub(crate) static LOCK: Mutex<()> = Mutex::new(());

    /// Exit status of a child whose `in_child` panicked.
    pub(crate) const PANICKED: i32 = 101;
    /// Exit status of a child whose wait for its release failed with an error other than `EINTR`.
    pub(crate) const WAIT_FAILED: i32 = 102;
    /// How long [`Child::wait`] waits for the child to exit before killing it and failing the test.
    const TIMEOUT: Duration = Duration::from_secs(30);

    /// A forked child. It runs a closure, then waits until it is released (or this process exits), then exits.
    #[derive(Debug)]
    pub(crate) struct Child {
        pid: libc::pid_t,
        release: Option<File>,
    }

    /// Forks; the child calls `in_child` (on its copy of this process's memory), then blocks reading a pipe until
    /// [`Child::wait`] or the handle's drop releases it, or until this process exits, and leaves with `_exit`: status
    /// 0, [`PANICKED`] if `in_child` panicked, or [`WAIT_FAILED`] if reading the pipe failed (an interrupted read is
    /// retried). The child never returns into the test harness and runs no exit handlers.
    ///
    /// The child of a multithreaded process may call only async-signal-safe functions. Waiting does (`close`,
    /// `read`, `_exit`); `in_child` is the caller's responsibility (allocating relies on the system allocator
    /// reinitialising its locks in the child, which glibc's and macOS's do).
    pub(crate) fn fork(in_child: impl FnOnce()) -> io::Result<Child> {
        let mut fds = [0 as libc::c_int; 2];
        // SAFETY: `fds` is a valid array of two descriptors for `pipe` to fill.
        if unsafe { libc::pipe(fds.as_mut_ptr()) } != 0 {
            return Err(super::last_os_error());
        }
        let [read_fd, write_fd] = fds;
        for fd in fds {
            // SAFETY: fcntl on a descriptor we just created. Close-on-exec keeps the pipe out of other tests' children
            // once they exec (they could inherit it before the flag is set; that only delays their EOF, not ours).
            unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) };
        }
        // SAFETY: `fork` has no memory-safety preconditions. The child below only runs `in_child` (see the function
        // documentation) and async-signal-safe calls, and leaves with `_exit` without returning.
        let pid = unsafe { libc::fork() };
        if pid < 0 {
            let err = super::last_os_error();
            // SAFETY: both descriptors are ours and still open.
            unsafe {
                libc::close(read_fd);
                libc::close(write_fd);
            }
            return Err(err);
        }
        if pid == 0 {
            let mut status = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(in_child))
            {
                Ok(()) => 0,
                Err(_) => PANICKED,
            };
            let mut byte = 0_u8;
            // SAFETY: the child's own copies of the pipe. Closing the write end first lets `read` see EOF if the parent
            // dies, so the child never outlives it for long. Reading the error code does not allocate.
            unsafe {
                libc::close(write_fd);
                // A byte (released) or end of file (released, or this process has gone) ends the wait; an interrupted
                // read must not, or the child would close its descriptors before the test is done with them.
                while libc::read(read_fd, (&raw mut byte).cast(), 1) < 0 {
                    if io::Error::last_os_error().raw_os_error() != Some(libc::EINTR) {
                        if status == 0 {
                            status = WAIT_FAILED;
                        }
                        break;
                    }
                }
            }
            exit(status);
        }
        // SAFETY: the parent's copy of the read end, which it does not use.
        unsafe { libc::close(read_fd) };
        Ok(Child {
            pid,
            // SAFETY: `write_fd` is open and owned by nothing else in this process.
            release: Some(unsafe { File::from_raw_fd(write_fd) }),
        })
    }

    /// Leaves the (forked child) process at once with `status`, without unwinding or running exit handlers.
    pub(crate) fn exit(status: i32) -> ! {
        // SAFETY: `_exit` is async-signal-safe and has no preconditions.
        unsafe { libc::_exit(status) }
    }

    /// Makes `signal` interrupt blocking calls in this process, and in children forked from it afterwards, instead of
    /// terminating it: installs a handler that does nothing, without `SA_RESTART`.
    pub(crate) fn interrupt_on(signal: libc::c_int) {
        extern "C" fn ignore(_: libc::c_int) {}
        // SAFETY: a zeroed `sigaction` is valid (empty mask, no flags); the handler is async-signal-safe (it does
        // nothing) and lives for the whole program.
        unsafe {
            let mut action: libc::sigaction = std::mem::zeroed();
            action.sa_sigaction = ignore as extern "C" fn(libc::c_int) as libc::sighandler_t;
            libc::sigaction(signal, &action, std::ptr::null_mut());
        }
    }

    /// Whether `fd` is an open descriptor in this process.
    pub(crate) fn is_open(fd: RawFd) -> bool {
        // SAFETY: F_GETFD only reads the descriptor's flags; on a closed descriptor it fails with EBADF.
        unsafe { libc::fcntl(fd, libc::F_GETFD) != -1 }
    }

    /// Why reaping a child failed.
    enum ReapError {
        /// It did not exit within [`TIMEOUT`] and was killed.
        TimedOut,
        /// `waitpid` failed.
        Wait(io::Error),
    }

    impl Child {
        /// Releases the child and returns its exit status (`None` if it did not exit normally).
        ///
        /// # Panics
        ///
        /// If the child does not exit within 30 seconds (it is then killed and reaped), or `waitpid` fails.
        pub(crate) fn wait(self) -> Option<i32> {
            self.wait_within(TIMEOUT)
        }

        /// [`Child::wait`], killing the child if it has not exited `timeout` after its release.
        pub(crate) fn wait_within(mut self, timeout: Duration) -> Option<i32> {
            let pid = self.pid;
            match self.reap(timeout) {
                Ok(status) => status,
                Err(e) => panic!("{}", e.message(pid, timeout)),
            }
        }

        /// Sends `signal` to the child.
        pub(crate) fn signal(&self, signal: libc::c_int) {
            // SAFETY: `pid` names our own child, which is not reaped before `self` is consumed or dropped.
            unsafe { libc::kill(self.pid, signal) };
        }

        /// Releases and reaps the child; `Ok(None)` if it was already reaped or did not exit normally.
        fn reap(&mut self, timeout: Duration) -> Result<Option<i32>, ReapError> {
            let Some(mut release) = self.release.take() else {
                return Ok(None);
            };
            // The child may have left already (if it exited from `in_child`): ignore EPIPE.
            let _ = release.write_all(&[1]);
            drop(release);
            let deadline = Instant::now() + timeout;
            let mut status = 0;
            loop {
                // SAFETY: polls our own child; `status` is a valid out-pointer.
                let rc = unsafe { libc::waitpid(self.pid, &mut status, libc::WNOHANG) };
                if rc == self.pid {
                    break;
                }
                if rc < 0 {
                    let err = io::Error::last_os_error();
                    if err.kind() != io::ErrorKind::Interrupted {
                        return Err(ReapError::Wait(err));
                    }
                } else if Instant::now() >= deadline {
                    // SAFETY: kills and reaps our own child, which has not been reaped (`rc` was 0), so `pid` still
                    // names it.
                    unsafe {
                        libc::kill(self.pid, libc::SIGKILL);
                        while libc::waitpid(self.pid, &mut status, 0) < 0
                            && io::Error::last_os_error().kind() == io::ErrorKind::Interrupted
                        {
                        }
                    }
                    return Err(ReapError::TimedOut);
                } else {
                    std::thread::sleep(Duration::from_millis(1));
                }
            }
            Ok(libc::WIFEXITED(status).then(|| libc::WEXITSTATUS(status)))
        }
    }

    impl ReapError {
        fn message(&self, pid: libc::pid_t, timeout: Duration) -> String {
            match self {
                ReapError::TimedOut => format!(
                    "forked child {pid} did not exit within {timeout:?} of its release (deadlocked?); killed it"
                ),
                ReapError::Wait(e) => format!("waiting for forked child {pid} failed: {e}"),
            }
        }
    }

    impl Drop for Child {
        fn drop(&mut self) {
            if let Err(e) = self.reap(TIMEOUT) {
                if !std::thread::panicking() {
                    panic!("{}", e.message(self.pid, TIMEOUT));
                }
            }
        }
    }
}

/// Reserves disk blocks for the first `len` bytes of `file` and sets its size to `len`, so that later writes into
/// that range don't need new blocks (modulo copy-on-write filesystems; see the crash contract).
pub(crate) fn preallocate(file: &File, len: u64) -> io::Result<()> {
    let len_off = libc::off_t::try_from(len)
        .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "segment too large"))?;
    #[cfg(any(target_os = "linux", target_os = "android"))]
    {
        // SAFETY: fallocate on a valid descriptor has no memory-safety preconditions.
        let rc = unsafe { libc::fallocate(file.as_raw_fd(), 0, 0, len_off) };
        if rc != 0 {
            return Err(last_os_error());
        }
        Ok(())
    }
    #[cfg(target_vendor = "apple")]
    {
        let mut store = libc::fstore_t {
            fst_flags: libc::F_ALLOCATECONTIG,
            fst_posmode: libc::F_PEOFPOSMODE,
            fst_offset: 0,
            fst_length: len_off,
            fst_bytesalloc: 0,
        };
        // SAFETY: F_PREALLOCATE takes a pointer to an `fstore_t`, which lives on our stack for the whole call.
        let mut rc = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_PREALLOCATE, &mut store) };
        if rc == -1 {
            store.fst_flags = libc::F_ALLOCATEALL;
            // SAFETY: as above.
            rc = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_PREALLOCATE, &mut store) };
        }
        if rc == -1 {
            return Err(last_os_error());
        }
        file.set_len(len)
    }
    #[cfg(not(any(target_os = "linux", target_os = "android", target_vendor = "apple")))]
    {
        let _ = len_off;
        file.set_len(len)
    }
}

/// `msync(MS_SYNC)` on the pages covering `[offset, offset + len)` of `file` (opened read-write), through a new shared
/// mapping of the whole file: for a segment whose earlier mapping is gone (a checkpoint of a released segment on macOS,
/// `checkpoint::steps`). The mapping is the file's, not the old one's, so the call writes back the file's dirty pages
/// in the range whichever mapping dirtied them.
pub(crate) fn msync_file(file: &File, offset: u64, len: u64) -> io::Result<()> {
    let size = usize::try_from(file.metadata()?.len())
        .map_err(|_| io::Error::other("file too large to map"))?;
    MapRw::new(file, size)?.sync_range(offset, len)
}

/// Flushes a file's data (and the metadata needed to read it) to the device: `fdatasync` on Linux, `fsync`
/// elsewhere. On macOS this does not flush the drive's cache; see [`full_barrier`].
pub(crate) fn sync_data(file: &File) -> io::Result<()> {
    #[cfg(any(target_os = "linux", target_os = "android"))]
    // SAFETY: fdatasync on a valid descriptor has no memory-safety preconditions.
    let rc = unsafe { libc::fdatasync(file.as_raw_fd()) };
    #[cfg(not(any(target_os = "linux", target_os = "android")))]
    // SAFETY: fsync on a valid descriptor has no memory-safety preconditions.
    let rc = unsafe { libc::fsync(file.as_raw_fd()) };
    if rc != 0 {
        Err(last_os_error())
    } else {
        Ok(())
    }
}

/// `fsync` (used for directories, whose entries must be persisted).
pub(crate) fn sync_all(file: &File) -> io::Result<()> {
    // SAFETY: fsync on a valid descriptor has no memory-safety preconditions.
    let rc = unsafe { libc::fsync(file.as_raw_fd()) };
    if rc != 0 {
        Err(last_os_error())
    } else {
        Ok(())
    }
}

/// The platform's strongest flush: on macOS `fcntl(F_FULLFSYNC)`, which asks the drive to flush its whole write
/// cache (failing with `ENOTSUP` where unsupported, which callers report rather than downgrade); elsewhere
/// [`sync_data`], because Linux's `fdatasync`/`fsync` already flush the device cache.
pub(crate) fn full_barrier(file: &File) -> io::Result<()> {
    #[cfg(target_vendor = "apple")]
    {
        // SAFETY: F_FULLFSYNC takes no argument and has no memory-safety preconditions.
        let rc = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_FULLFSYNC) };
        if rc == -1 {
            Err(last_os_error())
        } else {
            Ok(())
        }
    }
    #[cfg(not(target_vendor = "apple"))]
    {
        sync_data(file)
    }
}

/// Starts write-back of the dirty pages of `file` that overlap `[offset, offset + len)` without waiting for it:
/// `sync_file_range(SYNC_FILE_RANGE_WRITE)` (ADR 0038 → Early write-back). It makes nothing durable (no metadata,
/// no device cache flush) and reports no earlier write-back error: without the wait flags it does not check or
/// advance the file's write-back error state, so a later `fdatasync` on the same file still reports any failure of
/// this write-back. Linux only.
#[cfg(target_os = "linux")]
pub(crate) fn start_writeback(file: &File, offset: u64, len: u64) -> io::Result<()> {
    let (Ok(offset), Ok(len)) = (
        libc::off64_t::try_from(offset),
        libc::off64_t::try_from(len),
    ) else {
        return Err(io::Error::from(io::ErrorKind::InvalidInput));
    };
    // SAFETY: sync_file_range on a valid descriptor reads no memory of this process and has no memory-safety
    // preconditions; the range need not be mapped.
    let rc = unsafe {
        libc::sync_file_range(file.as_raw_fd(), offset, len, libc::SYNC_FILE_RANGE_WRITE)
    };
    if rc != 0 {
        Err(last_os_error())
    } else {
        Ok(())
    }
}

/// The CPUs a thread affinity mask can name here: 8,192, the largest `NR_CPUS` of the kernels tickertape supports.
/// The kernel ignores bits past its own number of CPUs.
#[cfg(target_os = "linux")]
pub(crate) const AFFINITY_CPUS: usize = 8192;

/// Sets the calling thread's CPU affinity to `cpus` (CPU numbers below [`AFFINITY_CPUS`]) with the
/// `sched_setaffinity` system call. The kernel intersects the mask with the CPUs the thread's cpuset allows and fails
/// with `EINVAL` if nothing is left. Linux only.
#[cfg(target_os = "linux")]
pub(crate) fn set_thread_affinity(cpus: impl IntoIterator<Item = usize>) -> io::Result<()> {
    let mut mask = vec![0u64; AFFINITY_CPUS / 64];
    for cpu in cpus {
        let word = mask
            .get_mut(cpu / 64)
            .ok_or_else(|| io::Error::from_raw_os_error(libc::EINVAL))?;
        *word |= 1 << (cpu % 64);
    }
    // SAFETY: the kernel reads `size_of_val(&mask)` bytes from `mask`'s buffer, which is that long and stays alive
    // for the call; pid 0 is the calling thread. The raw system call is used so that the C library cannot reject a
    // mask longer than its own `cpu_set_t`.
    let rc = unsafe {
        libc::syscall(
            libc::SYS_sched_setaffinity,
            0 as libc::pid_t,
            std::mem::size_of_val(mask.as_slice()),
            mask.as_ptr(),
        )
    };
    if rc != 0 {
        Err(last_os_error())
    } else {
        Ok(())
    }
}

/// The calling thread's CPU affinity: the CPU numbers in its mask (`sched_getaffinity`). Linux only; for tests.
#[cfg(all(target_os = "linux", test))]
pub(crate) fn thread_affinity() -> io::Result<Vec<usize>> {
    let mut mask = vec![0u64; AFFINITY_CPUS / 64];
    // SAFETY: the kernel writes at most `size_of_val(&mask)` bytes into `mask`'s buffer, which is that long and
    // stays alive for the call; pid 0 is the calling thread.
    let rc = unsafe {
        libc::syscall(
            libc::SYS_sched_getaffinity,
            0 as libc::pid_t,
            std::mem::size_of_val(mask.as_slice()),
            mask.as_mut_ptr(),
        )
    };
    if rc < 0 {
        return Err(last_os_error());
    }
    Ok((0..AFFINITY_CPUS)
        .filter(|cpu| mask[cpu / 64] & (1 << (cpu % 64)) != 0)
        .collect())
}

/// True if `err` means "no space" or "quota exceeded".
pub(crate) fn is_storage_full(err: &io::Error) -> bool {
    matches!(err.raw_os_error(), Some(code) if code == libc::ENOSPC || code == libc::EDQUOT)
}

/// A read-only mapping that isn't backed by a file, for tests that also run under Miri.
#[cfg(test)]
impl MapRo {
    /// An anonymous private mapping holding `bytes` (zero-padded to whole pages), made read-only where segments are
    /// mapped for reading ([`MAPPED_READS`]) and outside Miri (which doesn't model page protection).
    fn anonymous(bytes: &[u8]) -> MapRo {
        let page = page_size();
        let len = bytes.len().max(1).div_ceil(page) * page;
        // SAFETY: an anonymous private mapping with a null hint and a non-zero length has no memory-safety
        // preconditions; it returns fresh memory that nothing aliases, or MAP_FAILED (checked).
        let ptr = unsafe {
            libc::mmap(
                std::ptr::null_mut(),
                len,
                libc::PROT_READ | libc::PROT_WRITE,
                libc::MAP_PRIVATE | libc::MAP_ANON,
                -1,
                0,
            )
        };
        assert_ne!(ptr, libc::MAP_FAILED, "{}", last_os_error());
        let ptr = NonNull::new(ptr.cast::<u8>()).expect("mmap returned null");
        // SAFETY: the fresh mapping is writable, at least `bytes.len()` long, and no reference into it exists yet.
        unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr.as_ptr(), bytes.len()) };
        if MAPPED_READS && !cfg!(miri) {
            // SAFETY: changes the protection of exactly this fresh mapping; no reference into it exists yet.
            let rc = unsafe { libc::mprotect(ptr.as_ptr().cast(), len, libc::PROT_READ) };
            assert_eq!(rc, 0, "{}", last_os_error());
        }
        MapRo { ptr, len }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;

    /// The reader's loads, bounds and alignment on a mapping that also exists under Miri (where file mappings don't):
    /// Miri checks the pointer arithmetic of `load_u32`, `words` and `committed_bytes`; natively the memory is
    /// read-only, so any access other than a plain load would fault.
    #[test]
    fn map_ro_loads_validate_a_record_on_anonymous_memory() {
        use crate::format::{self, RecordHeader};
        let payload: Vec<u8> = (0..203_u32).map(|i| (i * 13 + 5) as u8).collect();
        let header = RecordHeader {
            seq: 9,
            schema_id: 3,
            venue_ts_ns: 11,
            local_ts_ns: 12,
        };
        let len = format::frame_len(payload.len()).unwrap();
        let mut image = vec![0u8; 64 + format::align8(u64::from(len)) as usize + 16];
        // The record at offset 64, then the next slot (empty) and a word of non-zero bytes after it.
        let body = &mut image[68..64 + len as usize];
        format::write_record_fields(&header, body);
        body[36..].copy_from_slice(&payload);
        format::finish_record_body(len, body);
        image[64..68].copy_from_slice(&len.to_le_bytes());
        let end = image.len();
        image[end - 8..].copy_from_slice(&[0xa5; 8]);
        let map = MapRo::anonymous(&image);
        let size = map.len;

        assert_eq!(map.commit_word(64), Some(len));
        let crc = map.load_u32(68).unwrap();
        assert_eq!(crc.to_le_bytes(), image[68..72]);
        let words = map
            .words(72, (format::align8(u64::from(len)) - 8) / 8)
            .unwrap();
        assert_eq!(format::decode_record_words(len, crc, words, 9), Ok(header));
        // SAFETY: the record was validated just above and nothing modifies this memory.
        let bytes = unsafe { map.committed_bytes(104, payload.len() as u64) }.unwrap();
        assert_eq!(bytes, &payload[..]);
        let next = 64 + format::align8(u64::from(len));
        assert_eq!(map.commit_word(next), Some(0));
        assert_eq!(
            map.words(next + 8, 1).unwrap().get(0),
            Some(0xa5a5_a5a5_a5a5_a5a5)
        );

        // Bounds and alignment at the end of the mapping.
        let last = size as u64;
        assert!(map.load_u32(last - 4).is_some());
        assert!(map.load_u32(last).is_none());
        assert!(map.load_u32(last - 2).is_none(), "misaligned");
        assert!(map.load_u32(u64::MAX - 3).is_none());
        assert_eq!(map.words(last - 8, 1).map(|w| w.len()), Some(1));
        assert!(map.words(last - 8, 2).is_none());
        assert!(map.words(last, 0).is_some_and(|w| w.len() == 0));
        assert!(map.words(last + 8, 0).is_none());
        assert!(map.words(4, 1).is_none(), "misaligned");
        assert!(map.words(8, u64::MAX / 4).is_none(), "overflowing length");
        assert!(map.words(u64::MAX - 7, 1).is_none(), "overflowing end");
        let all = map.words(0, last / 8).unwrap();
        assert_eq!(all.len() as u64, last / 8);
        assert_eq!(all.get(8), Some(u64::from(len) | u64::from(crc) << 32));
        assert_eq!(all.iter().count() as u64, last / 8);
        assert!(map.commit_word(last - 4).is_none());
        // SAFETY: out-of-bounds requests return None without touching memory.
        assert!(unsafe { map.committed_bytes(last - 1, 2) }.is_none());
    }

    fn temp_file(len: u64) -> (tempfile::TempDir, File) {
        let dir = tempfile::tempdir().unwrap();
        let file = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create_new(true)
            .open(dir.path().join("f"))
            .unwrap();
        preallocate(&file, len).unwrap();
        (dir, file)
    }

    #[test]
    fn rw_and_ro_mappings_share_bytes() {
        let (_dir, file) = temp_file(65536);
        let mut rw = MapRw::new(&file, 65536).unwrap();
        rw.bytes_mut(68, 4).unwrap().copy_from_slice(b"abcd");
        rw.store_commit_word(64, 40).unwrap();
        assert_eq!(rw.commit_word(64), Some(40));
        rw.sync_range(64, 8).unwrap();
        sync_data(&file).unwrap();
        let Some(ro) = map_ro_where_supported(&file, 65536) else {
            return;
        };
        assert_eq!(ro.commit_word(64), Some(40));
        assert_eq!(ro.load_u32(68), Some(u32::from_le_bytes(*b"abcd")));
        assert_eq!(ro.load_u32(66), None, "misaligned");
        assert_eq!(ro.load_u32(65532).map(|_| ()), Some(()));
        assert_eq!(ro.load_u32(65536), None);
        let words = ro.words(64, 2).unwrap();
        assert_eq!(words.len(), 2);
        assert_eq!(
            words.get(0),
            Some(40 | u64::from(u32::from_le_bytes(*b"abcd")) << 32)
        );
        assert_eq!(words.get(1), Some(0));
        assert_eq!(words.get(2), None);
        assert!(ro.words(68, 1).is_none(), "misaligned");
        assert!(ro.words(65528, 1).is_some());
        assert!(ro.words(65528, 2).is_none());
        assert!(ro.words(8, u64::MAX).is_none(), "overflowing length");
        // SAFETY: the bytes were written before the observed commit word and nothing modifies them afterwards.
        assert_eq!(unsafe { ro.committed_bytes(68, 4) }.unwrap(), b"abcd");
    }

    #[test]
    fn bounds_and_alignment_are_checked() {
        let (_dir, file) = temp_file(65536);
        let mut rw = MapRw::new(&file, 65536).unwrap();
        assert!(
            rw.commit_word(65532).is_none(),
            "4-aligned but not 8-aligned"
        );
        assert!(rw.commit_word(65536).is_none());
        assert!(rw.commit_word(65528).is_some());
        assert!(rw.bytes_mut(65530, 7).is_none());
        assert!(rw.bytes(u64::MAX, 2).is_none());
        let Some(ro) = map_ro_where_supported(&file, 65536) else {
            return;
        };
        assert!(ro.commit_word(4).is_none());
        // SAFETY: out-of-bounds requests return None without touching memory.
        assert!(unsafe { ro.committed_bytes(65535, 2) }.is_none());
    }

    #[test]
    fn lock_is_exclusive_across_handles() {
        let _forked = forked::LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("lock");
        let a = File::create(&path).unwrap();
        let b = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
        assert!(try_lock_exclusive(&a).unwrap());
        assert!(
            !try_lock_exclusive(&b).unwrap(),
            "flock locks are per open file description"
        );
        drop(a);
        assert!(try_lock_exclusive(&b).unwrap());
    }

    /// The fork helper kills a child that does not exit after its release and fails the test, instead of hanging.
    #[test]
    #[should_panic(expected = "did not exit within 100ms of its release (deadlocked?); killed it")]
    fn forked_child_that_never_exits_is_killed() {
        let _forked = forked::LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let child = forked::fork(|| {
            loop {
                std::thread::sleep(std::time::Duration::from_secs(1));
            }
        })
        .unwrap();
        child.wait_within(std::time::Duration::from_millis(100));
    }

    /// A signal interrupting the forked child's wait for its release must not end the wait: the child keeps its
    /// descriptors (here: the only copy holding a lock) until it is released.
    #[test]
    fn forked_child_keeps_waiting_when_its_wait_is_interrupted() {
        let _forked = forked::LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("lock");
        let locked = File::create(&path).unwrap();
        assert!(try_lock_exclusive(&locked).unwrap());
        // Installed before the fork, so the child has the handler from its first instruction: a signal that arrived
        // before the child had installed it itself would terminate the child and release the lock. Nothing sends
        // this signal to the test process, where the handler stays installed.
        forked::interrupt_on(libc::SIGUSR1);
        let child = forked::fork(|| {}).unwrap();
        drop(locked);
        let other = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(50));
        child.signal(libc::SIGUSR1);
        std::thread::sleep(std::time::Duration::from_millis(50));
        assert!(
            !try_lock_exclusive(&other).unwrap(),
            "the interrupted child must still hold its copy of the lock"
        );
        assert_eq!(child.wait(), Some(0));
        assert!(try_lock_exclusive(&other).unwrap());
    }

    /// Closing one descriptor of a locked open file description keeps the lock while another descriptor of it is
    /// open (as in a child forked before `exec`); `unlock` releases it for all of them.
    #[test]
    fn unlock_releases_a_lock_that_a_copied_descriptor_still_holds() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("lock");
        let a = File::create(&path).unwrap();
        let copy = a.try_clone().unwrap();
        let other = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
        assert!(try_lock_exclusive(&a).unwrap());
        drop(a);
        assert!(
            !try_lock_exclusive(&other).unwrap(),
            "the copy still holds the lock"
        );
        unlock(&copy).unwrap();
        assert!(try_lock_exclusive(&other).unwrap());
    }

    #[test]
    fn preallocate_sets_size_and_zeroes() {
        let (_dir, mut file) = temp_file(131072);
        assert_eq!(file.metadata().unwrap().len(), 131072);
        file.write_all(b"x").unwrap();
        sync_all(&file).unwrap();
        full_barrier(&file).unwrap();
        if let Some(ro) = map_ro_where_supported(&file, 131072) {
            assert_eq!(ro.commit_word(131064), Some(0));
        }
    }

    /// `MapRo::new` where segments are mapped for reading; elsewhere checks that it refuses with `Unsupported`
    /// (ADR 0027 → Supported targets) and returns `None`, so a test keeps its writer-side assertions there.
    fn map_ro_where_supported(file: &File, len: usize) -> Option<MapRo> {
        let mapped = MapRo::new(file, len);
        assert_eq!(
            mapped.is_ok(),
            MAPPED_READS,
            "MapRo::new: {:?}",
            mapped.as_ref().err()
        );
        match mapped {
            Ok(ro) => Some(ro),
            Err(e) => {
                assert_eq!(e.kind(), io::ErrorKind::Unsupported);
                None
            }
        }
    }

    /// Segments are mapped for reading exactly on x86-64 and aarch64, and refused (`Unsupported`, nothing mapped)
    /// everywhere else, where `Reader::open_mapped` reads with `pread` (ADR 0027 → Supported targets).
    #[test]
    fn mapped_reads_exactly_on_x86_64_and_aarch64() {
        assert_eq!(
            MAPPED_READS,
            cfg!(any(target_arch = "x86_64", target_arch = "aarch64"))
        );
        let (_dir, file) = temp_file(65536);
        let ro = map_ro_where_supported(&file, 65536);
        assert_eq!(ro.is_some(), MAPPED_READS);
        if !MAPPED_READS {
            let err = MapRo::new(&file, 65536).unwrap_err();
            assert_eq!(err.kind(), io::ErrorKind::Unsupported);
        }
    }

    #[test]
    fn notify_region_attach_checks_the_nonce_and_sees_publications() {
        let (owner, location) = Notify::create(0x1234_5678_9abc_def0).unwrap();
        assert!(Notify::attach(&location, 1).is_err(), "wrong nonce");
        let reader = Notify::attach(&location, 0x1234_5678_9abc_def0).unwrap();
        assert!(reader.writer_notifies());
        let seen = reader.begin_wait();
        owner.publish();
        // The counter moved, so the wait returns at once instead of after 10 s.
        let started = std::time::Instant::now();
        assert_eq!(
            reader.wait(seen, Duration::from_secs(10)),
            WaitOutcome::Returned
        );
        assert!(started.elapsed() < Duration::from_secs(5));
        reader.end_wait();
        reader.end_wait(); // never below zero
        drop(owner);
        assert!(
            !reader.writer_notifies(),
            "a dropped writer clears its flag"
        );
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn notify_attach_rejects_an_unsealed_region() {
        use std::os::fd::FromRawFd;
        // SAFETY: test only; memfd_create returns a fresh descriptor or -1 (checked).
        let fd = unsafe { libc::memfd_create(c"unsealed".as_ptr(), libc::MFD_CLOEXEC) };
        assert!(fd >= 0);
        // SAFETY: `fd` is fresh and owned by nothing else.
        let file = unsafe { File::from_raw_fd(fd) };
        file.set_len(NOTIFY_REGION_LEN as u64).unwrap();
        let location = NotifyLocation::Memfd {
            pid: std::process::id(),
            fd,
        };
        let err = Notify::attach(&location, 0).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData, "{err}");
    }

    #[test]
    fn notify_region_cannot_shrink() {
        let (owner, location) = Notify::create(7).unwrap();
        let file = &owner.owner.as_ref().unwrap().file;
        assert!(file.set_len(0).is_err(), "owner's descriptor");
        assert!(file.set_len(1).is_err());
        let other = open_region(&location).unwrap();
        assert!(
            other.set_len(0).is_err(),
            "another descriptor for the same region"
        );
        // macOS rounds the object up to a whole page (16 KiB on Apple silicon).
        assert!(other.metadata().unwrap().len() >= NOTIFY_REGION_LEN as u64);
    }

    #[test]
    fn storage_full_detection() {
        assert!(is_storage_full(&io::Error::from_raw_os_error(libc::ENOSPC)));
        assert!(!is_storage_full(&io::Error::from_raw_os_error(libc::EIO)));
    }
}