libxev-sys 0.0.1-rc.2

Low-level FFI bindings to libxev (built from vendored sources via Zig).
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
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
const std = @import("std");
const builtin = @import("builtin");
const assert = std.debug.assert;
const linux = std.os.linux;
const posix = std.posix;
const xev_posix = @import("../posix.zig");
const net = xev_posix.net;
const queue = @import("../queue.zig");
const queue_mpsc = @import("../queue_mpsc.zig");
const heap = @import("../heap.zig");
const ThreadPool = @import("../ThreadPool.zig");
const Async = @import("../main.zig").Epoll.Async;

/// In Zig 0.16, `std.posix.epoll_create1`, `epoll_ctl`, and `epoll_wait`
/// were removed. These helpers replicate the old wrappers using the raw
/// Linux syscall layer (`std.os.linux`).
const epoll_helper = struct {
    const EpollCreateError = error{
        ProcessFdQuotaExceeded,
        SystemFdQuotaExceeded,
        SystemResources,
        Unexpected,
    };

    fn epoll_create1(flags: u32) EpollCreateError!i32 {
        const rc = linux.epoll_create1(flags);
        switch (linux.errno(rc)) {
            .SUCCESS => return @intCast(rc),
            .MFILE => return error.ProcessFdQuotaExceeded,
            .NFILE => return error.SystemFdQuotaExceeded,
            .NOMEM => return error.SystemResources,
            else => return error.Unexpected,
        }
    }

    fn epoll_ctl(epfd: i32, op: u32, fd: i32, event: ?*linux.epoll_event) EpollCtlError!void {
        const rc = linux.epoll_ctl(epfd, op, fd, event);
        switch (linux.errno(rc)) {
            .SUCCESS => return,
            .EXIST => return error.FileDescriptorAlreadyPresentInSet,
            .LOOP => return error.OperationCausesCircularLoop,
            .NOENT => return error.FileDescriptorNotRegistered,
            .NOMEM => return error.SystemResources,
            .NOSPC => return error.UserResourceLimitReached,
            .PERM => return error.FileDescriptorIncompatibleWithEpoll,
            else => return error.Unexpected,
        }
    }

    fn epoll_wait(epfd: i32, events: []linux.epoll_event, timeout: i32) usize {
        while (true) {
            const rc = linux.epoll_wait(epfd, events.ptr, @intCast(events.len), timeout);
            switch (linux.errno(rc)) {
                .SUCCESS => return @intCast(rc),
                .INTR => continue,
                else => unreachable,
            }
        }
    }
};

const looppkg = @import("../loop.zig");
const Options = looppkg.Options;
const RunMode = looppkg.RunMode;
const Callback = looppkg.Callback(@This());
const CallbackAction = looppkg.CallbackAction;
const CompletionState = looppkg.CompletionState;
const noopCallback = looppkg.NoopCallback(@This());

/// True if epoll is available on this platform.
pub fn available() bool {
    return builtin.os.tag == .linux;
}

/// Epoll backend.
///
/// WARNING: this backend is a bit of a mess. It is missing features and in
/// general is in much poorer quality than all of the other backends. It
/// isn't meant to really be used yet. We should remodel this in the style of
/// the kqueue backend.
pub const Loop = struct {
    const TimerHeap = heap.Intrusive(Operation.Timer, void, Operation.Timer.less);
    const TaskCompletionQueue = queue_mpsc.Intrusive(Completion);

    fd: posix.fd_t,

    /// The eventfd that this epoll queue always has a filter for. Writing
    /// an empty message to this eventfd can be used to wake up the loop
    /// at any time. Waking up the loop via this eventfd won't trigger any
    /// particular completion, it just forces tick to cycle.
    eventfd: Async,

    /// The number of active completions. This DOES NOT include completions that
    /// are queued in the submissions queue.
    active: usize = 0,

    /// Our queue of submissions that we want to enqueue on the next tick.
    submissions: queue.Intrusive(Completion) = .{},

    /// The queue for completions to delete from the epoll fd.
    deletions: queue.Intrusive(Completion) = .{},

    /// Heap of timers.
    timers: TimerHeap = .{ .context = {} },

    /// The thread pool to use for blocking operations that epoll can't do.
    thread_pool: ?*ThreadPool,

    /// The MPSC queue for completed completions from the thread pool.
    thread_pool_completions: TaskCompletionQueue,

    /// Cached time
    cached_now: posix.timespec,

    /// Some internal fields we can pack for better space.
    flags: packed struct {
        /// True once it is initialized.
        init: bool = false,

        /// Whether we're in a run or not (to prevent nested runs).
        in_run: bool = false,

        /// Whether our loop is in a stopped state or not.
        stopped: bool = false,
    } = .{},

    pub fn init(options: Options) !Loop {
        var eventfd = try Async.init();
        errdefer eventfd.deinit();

        var res: Loop = .{
            .fd = try epoll_helper.epoll_create1(std.os.linux.EPOLL.CLOEXEC),
            .eventfd = eventfd,
            .thread_pool = options.thread_pool,
            .thread_pool_completions = undefined,
            .cached_now = undefined,
        };
        res.update_now();
        return res;
    }

    pub fn deinit(self: *Loop) void {
        xev_posix.close(self.fd);
        self.eventfd.deinit();
    }

    /// Run the event loop. See RunMode documentation for details on modes.
    /// Once the loop is run, the pointer MUST remain stable.
    pub fn run(self: *Loop, mode: RunMode) !void {
        switch (mode) {
            .no_wait => try self.tick(0),
            .once => try self.tick(1),
            .until_done => while (!self.done()) try self.tick(1),
        }
    }

    fn done(self: *Loop) bool {
        return self.flags.stopped or (self.active == 0 and
            self.submissions.empty());
    }

    /// Stop the loop. This can only be called from the main thread.
    /// This will stop the loop forever. Future ticks will do nothing.
    ///
    /// This does NOT stop any completions that are queued to be executed
    /// in the thread pool. If you are using a thread pool, completions
    /// are not safe to recover until the thread pool is shut down. If
    /// you're not using a thread pool, all completions are safe to
    /// read/write once any outstanding `run` or `tick` calls are returned.
    pub fn stop(self: *Loop) void {
        self.flags.stopped = true;
    }

    /// Returns true if the loop is stopped. This may mean there
    /// are still pending completions to be processed.
    pub fn stopped(self: *Loop) bool {
        return self.flags.stopped;
    }

    /// Add a completion to the loop.
    pub fn add(self: *Loop, completion: *Completion) void {
        switch (completion.flags.state) {
            // Already adding, forget about it.
            .adding => return,

            // If it is dead we're good. If we're deleting we'll ignore it
            // while we're processing.
            .dead,
            .deleting,
            => {},

            .active => unreachable,
        }
        completion.flags.state = .adding;

        // We just add the completion to the queue. Failures can happen
        // at tick time...
        self.submissions.push(completion);
    }

    /// Delete a completion from the loop.
    pub fn delete(self: *Loop, completion: *Completion) void {
        switch (completion.flags.state) {
            // Already deleted
            .deleting => return,

            // If we're active then we will stop it and remove from epoll.
            // If we're adding then we'll ignore it when adding.
            .dead, .active, .adding => {},
        }
        completion.flags.state = .deleting;

        self.deletions.push(completion);
    }

    /// Returns the "loop" time in milliseconds. The loop time is updated
    /// once per loop tick, before IO polling occurs. It remains constant
    /// throughout callback execution.
    ///
    /// You can force an update of the "now" value by calling update_now()
    /// at any time from the main thread.
    ///
    /// The clock that is used is not guaranteed. In general, a monotonic
    /// clock source is always used if available. This value should typically
    /// just be used for relative time calculations within the loop, such as
    /// answering the question "did this happen <x> ms ago?".
    pub fn now(self: *Loop) i64 {
        // If anything overflows we just return the max value.
        const max = std.math.maxInt(i64);

        // Calculate all the values, being careful about overflows in order
        // to just return the maximum value.
        const sec = std.math.mul(isize, self.cached_now.sec, std.time.ms_per_s) catch return max;
        const nsec = @divFloor(self.cached_now.nsec, std.time.ns_per_ms);
        return std.math.lossyCast(i64, sec +| nsec);
    }

    /// Update the cached time.
    pub fn update_now(self: *Loop) void {
        var ts: std.os.linux.timespec = undefined;
        const rc = std.os.linux.clock_gettime(std.os.linux.CLOCK.MONOTONIC, &ts);
        if (linux.errno(rc) == .SUCCESS) {
            self.cached_now = ts;
        }
    }

    /// Add a timer to the loop. The timer will execute in "next_ms". This
    /// is oneshot: the timer will not repeat. To repeat a timer, either
    /// schedule another in your callback or return rearm from the callback.
    pub fn timer(
        self: *Loop,
        c: *Completion,
        next_ms: u64,
        userdata: ?*anyopaque,
        comptime cb: Callback,
    ) void {
        c.* = .{
            .op = .{
                .timer = .{
                    .next = self.timer_next(next_ms),
                },
            },
            .userdata = userdata,
            .callback = cb,
        };

        self.add(c);
    }

    /// See io_uring.timer_reset for docs.
    pub fn timer_reset(
        self: *Loop,
        c: *Completion,
        c_cancel: *Completion,
        next_ms: u64,
        userdata: ?*anyopaque,
        comptime cb: Callback,
    ) void {
        switch (c.flags.state) {
            .dead, .deleting => {
                self.timer(c, next_ms, userdata, cb);
                return;
            },

            // Adding state we can just modify the metadata and return
            // since the timer isn't in the heap yet.
            .adding => {
                c.op.timer.next = self.timer_next(next_ms);
                c.userdata = userdata;
                c.callback = cb;
                return;
            },

            .active => {
                // Update the reset time for the timer to the desired time
                // along with all the callbacks.
                c.op.timer.reset = self.timer_next(next_ms);
                c.userdata = userdata;
                c.callback = cb;

                // If the cancellation is active, we assume its for this timer
                // and do nothing.
                if (c_cancel.state() == .active) return;
                assert(c_cancel.state() == .dead and c.state() == .active);
                c_cancel.* = .{ .op = .{ .cancel = .{ .c = c } } };
                self.add(c_cancel);
            },
        }
    }

    fn timer_next(self: *Loop, next_ms: u64) posix.timespec {
        // Get the timestamp of the absolute time that we'll execute this timer.
        // There are lots of failure scenarios here in math. If we see any
        // of them we just use the maximum value.
        const max: posix.timespec = .{
            .sec = std.math.maxInt(isize),
            .nsec = std.math.maxInt(isize),
        };

        const next_s = std.math.cast(isize, next_ms / std.time.ms_per_s) orelse
            return max;
        const next_ns = std.math.cast(
            isize,
            (next_ms % std.time.ms_per_s) * std.time.ns_per_ms,
        ) orelse return max;

        return .{
            .sec = std.math.add(isize, self.cached_now.sec, next_s) catch
                return max,
            .nsec = std.math.add(isize, self.cached_now.nsec, next_ns) catch
                return max,
        };
    }

    /// Tick through the event loop once, waiting for at least "wait" completions
    /// to be processed by the loop itself.
    pub fn tick(self: *Loop, wait: u32) !void {
        // If we're stopped then the loop is fully over.
        if (self.flags.stopped) return;

        // We can't nest runs.
        if (self.flags.in_run) return error.NestedRunsNotAllowed;
        self.flags.in_run = true;
        defer self.flags.in_run = false;

        // Initialize
        if (!self.flags.init) {
            self.flags.init = true;

            if (self.thread_pool != null) {
                self.thread_pool_completions.init();
            }

            var ev: linux.epoll_event = .{
                .events = linux.EPOLL.IN | linux.EPOLL.RDHUP,
                .data = .{ .fd = self.eventfd.fd },
            };
            epoll_helper.epoll_ctl(
                self.fd,
                linux.EPOLL.CTL_ADD,
                self.eventfd.fd,
                &ev,
            ) catch |err| {
                // We reset initialization because we can't do anything
                // safely unless we get this mach port registered!
                self.flags.init = false;
                return err;
            };
        }

        // Submit all the submissions. We copy the submission queue so that
        // any resubmits don't cause an infinite loop.
        var wait_rem: usize = @intCast(wait);
        var queued = self.submissions;
        self.submissions = .{};
        while (queued.pop()) |c| {
            // We ignore any completions that aren't in the adding state.
            // This usually means that we switched them to be deleted or
            // something.
            if (c.flags.state != .adding) continue;

            // These operations happen synchronously. Ensure they are
            // decremented from wait_rem.
            switch (c.op) {
                .cancel,
                // should noop be counted?
                // .noop,
                .shutdown,
                .timer,
                => wait_rem -|= 1,
                else => {},
            }

            self.start(c);
        }

        // Handle all deletions so we don't wait for them.
        while (self.deletions.pop()) |c| {
            if (c.flags.state != .deleting) continue;
            self.stop_completion(c);
        }

        // If we have no active handles then we return no matter what.
        if (self.active == 0) {
            // We still have to update our concept of "now".
            self.update_now();
            return;
        }

        // Wait and process events. We only do this if we have any active.
        var events: [1024]linux.epoll_event = undefined;
        while (self.active > 0 and (wait == 0 or wait_rem > 0)) {
            self.update_now();
            const now_timer: Operation.Timer = .{ .next = self.cached_now };

            // Run our expired timers
            while (self.timers.peek()) |t| {
                if (!Operation.Timer.less({}, t, &now_timer)) break;

                // Remove the timer
                assert(self.timers.deleteMin().? == t);

                // Mark completion as done
                const c = t.c;
                c.flags.state = .dead;
                self.active -= 1;

                // Lower our remaining count
                wait_rem -|= 1;

                // Invoke
                const action = c.callback(c.userdata, self, c, .{
                    .timer = .expiration,
                });
                switch (action) {
                    .disarm => {},
                    .rearm => self.start(c),
                }
            }

            // Run our completed thread pool work
            if (self.thread_pool != null) {
                while (self.thread_pool_completions.pop()) |c| {
                    // Mark completion as done
                    c.flags.state = .dead;
                    self.active -= 1;

                    // Lower our remaining count
                    wait_rem -|= 1;

                    // Invoke
                    const action = c.callback(c.userdata, self, c, c.task_result);
                    switch (action) {
                        .disarm => {},
                        .rearm => self.start(c),
                    }
                }
            }

            // Determine our next timeout based on the timers
            const timeout: i32 = if (wait_rem == 0) 0 else timeout: {
                // If we have a timer, we want to set the timeout to our next
                // timer value. If we have no timer, we wait forever.
                const t = self.timers.peek() orelse break :timeout -1;

                // Determine the time in milliseconds.
                const ms_now = @as(u64, @intCast(self.cached_now.sec)) * std.time.ms_per_s +
                    @as(u64, @intCast(self.cached_now.nsec)) / std.time.ns_per_ms;
                const ms_next = @as(u64, @intCast(t.next.sec)) * std.time.ms_per_s +
                    @as(u64, @intCast(t.next.nsec)) / std.time.ns_per_ms;
                break :timeout @as(i32, @intCast(ms_next -| ms_now));
            };

            const n = epoll_helper.epoll_wait(self.fd, &events, timeout);

            // Process all our events and invoke their completion handlers
            for (events[0..n]) |ev| {
                // Handle wakeup eventfd
                if (ev.data.fd == self.eventfd.fd) {
                    var buffer: u64 = undefined;
                    _ = xev_posix.read(self.eventfd.fd, std.mem.asBytes(&buffer)) catch {};
                    continue;
                }

                const c: *Completion = @ptrFromInt(@as(usize, @intCast(ev.data.ptr)));

                // We get the fd and mark this as in progress we can properly
                // clean this up late.r
                const fd = if (c.flags.dup) c.flags.dup_fd else c.fd();
                const close_dup = c.flags.dup;
                c.flags.state = .dead;

                const res = c.perform();
                const action = c.callback(c.userdata, self, c, res);
                switch (action) {
                    .disarm => {
                        // We can't use self.stop because we can't trust
                        // that c is still a valid pointer.
                        if (fd) |v| {
                            epoll_helper.epoll_ctl(
                                self.fd,
                                linux.EPOLL.CTL_DEL,
                                v,
                                null,
                            ) catch unreachable;

                            if (close_dup) {
                                xev_posix.close(v);
                            }
                        }

                        self.active -= 1;
                    },

                    // For epoll, epoll remains armed by default. We have to
                    // reset the state, that is all.
                    .rearm => c.flags.state = .active,
                }
            }

            if (wait == 0) break;
            wait_rem -|= n;
        }
    }

    /// Shedule a completion to run on a thread.
    fn thread_schedule(self: *Loop, c: *Completion) !void {
        const pool = self.thread_pool orelse return error.ThreadPoolRequired;

        // Setup our completion state so that thread_perform can do stuff
        c.task_loop = self;
        c.task_completions = &self.thread_pool_completions;
        c.task = .{ .callback = Loop.thread_perform };

        // We need to mark this completion as active before we schedule.
        c.flags.state = .active;
        self.active += 1;

        // Schedule it, from this point forward its not safe to touch c.
        pool.schedule(ThreadPool.Batch.from(&c.task));
    }

    /// This is the main callback for the threadpool to perform work
    /// on completions for the loop.
    fn thread_perform(t: *ThreadPool.Task) void {
        const c: *Completion = @fieldParentPtr("task", t);

        // Do our task
        c.task_result = c.perform();

        // Add to our completion queue
        c.task_completions.push(c);

        // Wake up our main loop
        c.task_loop.wakeup() catch {};
    }

    /// Sends an empty message to this loop's eventfd so that it wakes up.
    fn wakeup(self: *Loop) !void {
        try self.eventfd.notify();
    }

    fn start(self: *Loop, completion: *Completion) void {
        const res_: ?Result = switch (completion.op) {
            .noop => {
                completion.flags.state = .dead;
                return;
            },

            .cancel => |v| res: {
                if (completion.flags.threadpool) {
                    break :res .{ .cancel = error.ThreadPoolUnsupported };
                }

                // We stop immediately. We only stop if we are in the
                // "adding" state because cancellation or any other action
                // means we're complete already.
                if (completion.flags.state == .adding) {
                    if (v.c.op == .cancel) @panic("cannot cancel a cancellation");
                    self.stop_completion(v.c);
                }

                // We always run timers
                break :res .{ .cancel = {} };
            },

            .accept => res: {
                var ev: linux.epoll_event = .{
                    .events = linux.EPOLL.IN,
                    .data = .{ .ptr = @intFromPtr(completion) },
                };

                const fd = completion.fd_maybe_dup() catch |err| break :res .{ .accept = err };
                break :res if (epoll_helper.epoll_ctl(
                    self.fd,
                    linux.EPOLL.CTL_ADD,
                    fd,
                    &ev,
                )) null else |err| .{ .accept = err };
            },

            .connect => |*v| res: {
                const fd = completion.fd_maybe_dup() catch |err| break :res .{ .connect = err };

                if (xev_posix.connect(fd, &v.addr.any, v.addr.getOsSockLen())) {
                    break :res .{ .connect = {} };
                } else |err| switch (err) {
                    // If we would block then we register with epoll
                    error.WouldBlock => {},

                    // Any other error we just return immediately
                    else => break :res .{ .connect = err },
                }

                // If connect returns WouldBlock then we register for OUT events
                // and are notified of connection completion that way.
                var ev: linux.epoll_event = .{
                    .events = linux.EPOLL.OUT,
                    .data = .{ .ptr = @intFromPtr(completion) },
                };

                break :res if (epoll_helper.epoll_ctl(
                    self.fd,
                    linux.EPOLL.CTL_ADD,
                    fd,
                    &ev,
                )) null else |err| .{ .connect = err };
            },

            .read => res: {
                if (completion.flags.threadpool) {
                    if (self.thread_schedule(completion)) |_|
                        return
                    else |err|
                        break :res .{ .read = err };
                }

                var ev: linux.epoll_event = .{
                    .events = linux.EPOLL.IN | linux.EPOLL.RDHUP,
                    .data = .{ .ptr = @intFromPtr(completion) },
                };

                const fd = completion.fd_maybe_dup() catch |err| break :res .{ .read = err };
                break :res if (epoll_helper.epoll_ctl(
                    self.fd,
                    linux.EPOLL.CTL_ADD,
                    fd,
                    &ev,
                )) null else |err| .{ .read = err };
            },

            .pread => res: {
                if (completion.flags.threadpool) {
                    if (self.thread_schedule(completion)) |_|
                        return
                    else |err|
                        break :res .{ .read = err };
                }

                var ev: linux.epoll_event = .{
                    .events = linux.EPOLL.IN | linux.EPOLL.RDHUP,
                    .data = .{ .ptr = @intFromPtr(completion) },
                };

                const fd = completion.fd_maybe_dup() catch |err| break :res .{ .read = err };
                break :res if (epoll_helper.epoll_ctl(
                    self.fd,
                    linux.EPOLL.CTL_ADD,
                    fd,
                    &ev,
                )) null else |err| .{ .read = err };
            },

            .write => res: {
                if (completion.flags.threadpool) {
                    if (self.thread_schedule(completion)) |_|
                        return
                    else |err|
                        break :res .{ .write = err };
                }

                var ev: linux.epoll_event = .{
                    .events = linux.EPOLL.OUT,
                    .data = .{ .ptr = @intFromPtr(completion) },
                };

                const fd = completion.fd_maybe_dup() catch |err| break :res .{ .write = err };
                break :res if (epoll_helper.epoll_ctl(
                    self.fd,
                    linux.EPOLL.CTL_ADD,
                    fd,
                    &ev,
                )) null else |err| .{ .write = err };
            },

            .pwrite => res: {
                if (completion.flags.threadpool) {
                    if (self.thread_schedule(completion)) |_|
                        return
                    else |err|
                        break :res .{ .write = err };
                }

                var ev: linux.epoll_event = .{
                    .events = linux.EPOLL.OUT,
                    .data = .{ .ptr = @intFromPtr(completion) },
                };

                const fd = completion.fd_maybe_dup() catch |err| break :res .{ .write = err };
                break :res if (epoll_helper.epoll_ctl(
                    self.fd,
                    linux.EPOLL.CTL_ADD,
                    fd,
                    &ev,
                )) null else |err| .{ .write = err };
            },

            .send => res: {
                var ev: linux.epoll_event = .{
                    .events = linux.EPOLL.OUT,
                    .data = .{ .ptr = @intFromPtr(completion) },
                };

                const fd = completion.fd_maybe_dup() catch |err| break :res .{ .send = err };
                break :res if (epoll_helper.epoll_ctl(
                    self.fd,
                    linux.EPOLL.CTL_ADD,
                    fd,
                    &ev,
                )) null else |err| .{ .send = err };
            },

            .recv => res: {
                var ev: linux.epoll_event = .{
                    .events = linux.EPOLL.IN | linux.EPOLL.RDHUP,
                    .data = .{ .ptr = @intFromPtr(completion) },
                };

                const fd = completion.fd_maybe_dup() catch |err| break :res .{ .recv = err };
                break :res if (epoll_helper.epoll_ctl(
                    self.fd,
                    linux.EPOLL.CTL_ADD,
                    fd,
                    &ev,
                )) null else |err| .{ .recv = err };
            },

            .sendmsg => |*v| res: {
                if (v.buffer) |_| {
                    @panic("TODO: sendmsg with buffer");
                }

                var ev: linux.epoll_event = .{
                    .events = linux.EPOLL.OUT,
                    .data = .{ .ptr = @intFromPtr(completion) },
                };

                const fd = completion.fd_maybe_dup() catch |err| break :res .{ .sendmsg = err };
                break :res if (epoll_helper.epoll_ctl(
                    self.fd,
                    linux.EPOLL.CTL_ADD,
                    fd,
                    &ev,
                )) null else |err| .{ .sendmsg = err };
            },

            .recvmsg => res: {
                var ev: linux.epoll_event = .{
                    .events = linux.EPOLL.IN | linux.EPOLL.RDHUP,
                    .data = .{ .ptr = @intFromPtr(completion) },
                };

                const fd = completion.fd_maybe_dup() catch |err| break :res .{ .recvmsg = err };
                break :res if (epoll_helper.epoll_ctl(
                    self.fd,
                    linux.EPOLL.CTL_ADD,
                    fd,
                    &ev,
                )) null else |err| .{ .recvmsg = err };
            },

            .close => |v| res: {
                if (completion.flags.threadpool) {
                    if (self.thread_schedule(completion)) |_|
                        return
                    else |err|
                        break :res .{ .close = err };
                }

                xev_posix.close(v.fd);
                break :res .{ .close = {} };
            },

            .shutdown => |v| res: {
                const how_int: i32 = switch (v.how) {
                    .recv => linux.SHUT.RD,
                    .send => linux.SHUT.WR,
                    .both => linux.SHUT.RDWR,
                };
                const rc = linux.shutdown(v.socket, how_int);
                break :res .{ .shutdown = switch (linux.errno(rc)) {
                    .SUCCESS => {},
                    .NOTCONN => error.SocketNotConnected,
                    .NOBUFS => error.SystemResources,
                    else => |err| posix.unexpectedErrno(err),
                } };
            },

            .timer => |*v| res: {
                // Point back to completion since we need this. In the future
                // we want to use @fieldParentPtr but https://github.com/ziglang/zig/issues/6611
                v.c = completion;

                // Insert the timer into our heap.
                self.timers.insert(v);

                // We always run timers
                break :res null;
            },

            .poll => |v| res: {
                var ev: linux.epoll_event = .{
                    .events = v.events,
                    .data = .{ .ptr = @intFromPtr(completion) },
                };

                const fd = completion.fd_maybe_dup() catch |err| break :res .{ .poll = err };
                break :res if (epoll_helper.epoll_ctl(
                    self.fd,
                    linux.EPOLL.CTL_ADD,
                    fd,
                    &ev,
                )) null else |err| .{ .poll = err };
            },
        };

        // If we failed to add the completion then we call the callback
        // immediately and mark the error.
        if (res_) |res| {
            completion.flags.state = .dead;

            switch (completion.callback(
                completion.userdata,
                self,
                completion,
                res,
            )) {
                .disarm => {},

                // If we rearm then we requeue this. Due to the way that tick works,
                // this won't try to re-add immediately it won't happen until the
                // next tick.
                .rearm => self.add(completion),
            }

            return;
        }

        // If the completion was requested on a threadpool we should
        // never reach her.
        assert(!completion.flags.threadpool);

        // Mark the completion as active if we reached this point
        completion.flags.state = .active;

        // Increase our active count
        self.active += 1;
    }

    fn stop_completion(self: *Loop, completion: *Completion) void {
        // Delete. This should never fail.
        const maybe_fd = if (completion.flags.dup) completion.flags.dup_fd else completion.fd();
        if (maybe_fd) |fd| {
            epoll_helper.epoll_ctl(
                self.fd,
                linux.EPOLL.CTL_DEL,
                fd,
                null,
            ) catch unreachable;
        } else switch (completion.op) {
            .timer => |*v| {
                const c = v.c;

                if (c.flags.state == .active) {
                    // Timers needs to be removed from the timer heap.
                    self.timers.remove(v);
                }

                // If the timer was never fired, we need to fire it with
                // the cancellation notice.
                if (c.flags.state != .dead) {
                    // If we have reset set AND we got a cancellation result,
                    // that means that we were canceled so that we can update
                    // our expiration time.
                    if (v.reset) |r| {
                        v.next = r;
                        v.reset = null;
                        self.active -= 1;
                        self.start(c);
                        return;
                    }

                    const action = c.callback(c.userdata, self, c, .{ .timer = .cancel });
                    switch (action) {
                        .disarm => {},
                        .rearm => {
                            self.active -= 1;
                            self.start(c);
                            return;
                        },
                    }
                }
            },

            else => unreachable,
        }

        // Decrement the active count so we know how many are running for
        // .until_done run semantics.
        if (completion.flags.state == .active) self.active -= 1;

        // Mark the completion as done
        completion.flags.state = .dead;
    }
};

pub const Completion = struct {
    /// Operation to execute. This is only safe to read BEFORE the completion
    /// is queued. After being queued (with "add"), the operation may change.
    op: Operation = .{ .noop = {} },

    /// Userdata and callback for when the completion is finished.
    userdata: ?*anyopaque = null,
    callback: Callback = noopCallback,

    //---------------------------------------------------------------
    // Internal fields

    /// If scheduled on a thread pool, this will be set. This is NOT a
    /// reliable way to get access to the loop and shouldn't be used
    /// except internally.
    task: ThreadPool.Task = undefined,
    task_loop: *Loop = undefined,
    task_completions: *Loop.TaskCompletionQueue = undefined,
    task_result: Result = undefined,

    flags: packed struct {
        /// Watch state of this completion. We use this to determine whether
        /// we're active, adding, deleting, etc. This lets us add and delete
        /// multiple times before a loop tick and handle the state properly.
        state: State = .dead,

        /// Schedule this onto the threadpool rather than epoll. Not all
        /// operations support this.
        threadpool: bool = false,

        /// Set to true to dup the file descriptor for the operation prior
        /// to setting it up with epoll. This is a hack to make it so that
        /// a completion can represent a single op per fd, since epoll requires
        /// a single fd for multiple ops. We don't want to track that esp
        /// since epoll isn't the primary Linux interface.
        dup: bool = false,
        dup_fd: posix.fd_t = 0,
    } = .{},

    /// Intrusive queue field
    next: ?*Completion = null,

    const State = enum(u3) {
        /// completion is not part of any loop
        dead = 0,

        /// completion is in the submission queue
        adding = 1,

        /// completion is in the deletion queue
        deleting = 2,

        /// completion is registered with epoll
        active = 3,
    };

    /// Returns the state of this completion. There are some things to
    /// be caution about when calling this function.
    ///
    /// First, this is only safe to call from the main thread. This cannot
    /// be called from any other thread.
    ///
    /// Second, if you are using default "undefined" completions, this will
    /// NOT return a valid value if you access it. You must zero your
    /// completion using ".{}". You only need to zero the completion once.
    /// Once the completion is in use, it will always be valid.
    ///
    /// Third, if you stop the loop (loop.stop()), the completions registered
    /// with the loop will NOT be reset to a dead state.
    pub fn state(self: Completion) CompletionState {
        return switch (self.flags.state) {
            .dead => .dead,
            .adding, .deleting, .active => .active,
        };
    }

    /// Perform the operation associated with this completion. This will
    /// perform the full blocking operation for the completion.
    fn perform(self: *Completion) Result {
        return switch (self.op) {
            // This should never happen because we always do these synchronously
            // or in another location.
            .cancel,
            .noop,
            .shutdown,
            .timer,
            => unreachable,

            .accept => |*op| .{
                .accept = if (xev_posix.accept(
                    op.socket,
                    &op.addr,
                    &op.addr_size,
                    op.flags,
                )) |v|
                    v
                else |_|
                    error.Unknown,
            },

            .connect => |*op| .{
                .connect = if (xev_posix.getsockoptError(op.socket)) {} else |err| err,
            },

            .poll => .{ .poll = {} },

            .read => |*op| res: {
                const n_ = switch (op.buffer) {
                    .slice => |v| xev_posix.read(op.fd, v),
                    .array => |*v| xev_posix.read(op.fd, v),
                };

                break :res .{
                    .read = if (n_) |n|
                        if (n == 0) error.EOF else n
                    else |err|
                        err,
                };
            },

            .pread => |*op| res: {
                const n_ = switch (op.buffer) {
                    .slice => |v| xev_posix.pread(op.fd, v, op.offset),
                    .array => |*v| xev_posix.pread(op.fd, v, op.offset),
                };

                break :res .{
                    .pread = if (n_) |n|
                        if (n == 0) error.EOF else n
                    else |err|
                        err,
                };
            },

            .write => |*op| .{
                .write = switch (op.buffer) {
                    .slice => |v| xev_posix.write(op.fd, v),
                    .array => |*v| xev_posix.write(op.fd, v.array[0..v.len]),
                },
            },

            .pwrite => |*op| .{
                .pwrite = switch (op.buffer) {
                    .slice => |v| xev_posix.pwrite(op.fd, v, op.offset),
                    .array => |*v| xev_posix.pwrite(op.fd, v.array[0..v.len], op.offset),
                },
            },

            .send => |*op| .{
                .send = switch (op.buffer) {
                    .slice => |v| xev_posix.send(op.fd, v, 0),
                    .array => |*v| xev_posix.send(op.fd, v.array[0..v.len], 0),
                },
            },

            .sendmsg => |*op| .{
                .sendmsg = if (xev_posix.sendmsg(op.fd, op.msghdr, 0)) |v|
                    v
                else |err|
                    err,
            },

            .recvmsg => |*op| res: {
                const res = std.os.linux.recvmsg(op.fd, op.msghdr, 0);
                break :res .{
                    .recvmsg = if (res == 0)
                        error.EOF
                    else if (res > 0)
                        res
                    else switch (linux.errno(res)) {
                        else => |err| posix.unexpectedErrno(err),
                    },
                };
            },

            .recv => |*op| res: {
                const n_ = switch (op.buffer) {
                    .slice => |v| xev_posix.recv(op.fd, v, 0),
                    .array => |*v| xev_posix.recv(op.fd, v, 0),
                };

                break :res .{
                    .recv = if (n_) |n|
                        if (n == 0) error.EOF else n
                    else |err|
                        err,
                };
            },

            .close => |*op| res: {
                xev_posix.close(op.fd);
                break :res .{ .close = {} };
            },
        };
    }

    /// Return the fd for the completion. This will perform a dup(2) if
    /// requested.
    fn fd_maybe_dup(self: *Completion) error{DupFailed}!posix.fd_t {
        const old_fd = self.fd().?;
        if (!self.flags.dup) return old_fd;
        if (self.flags.dup_fd > 0) return self.flags.dup_fd;

        self.flags.dup_fd = xev_posix.dup(old_fd) catch return error.DupFailed;
        return self.flags.dup_fd;
    }

    /// Returns the fd associated with the completion (if any).
    fn fd(self: *Completion) ?posix.fd_t {
        return switch (self.op) {
            .accept => |v| v.socket,
            .connect => |v| v.socket,
            .poll => |v| v.fd,
            .read => |v| v.fd,
            .pread => |v| v.fd,
            .recv => |v| v.fd,
            .write => |v| v.fd,
            .pwrite => |v| v.fd,
            .send => |v| v.fd,
            .sendmsg => |v| v.fd,
            .recvmsg => |v| v.fd,
            .close => |v| v.fd,
            .shutdown => |v| v.socket,

            .cancel,
            .timer,
            => null,

            .noop => unreachable,
        };
    }
};

pub const OperationType = enum {
    noop,
    cancel,
    accept,
    connect,
    poll,
    read,
    pread,
    write,
    pwrite,
    send,
    recv,
    sendmsg,
    recvmsg,
    close,
    shutdown,
    timer,
};

/// The result type based on the operation type. For a callback, the
/// result tag will ALWAYS match the operation tag.
pub const Result = union(OperationType) {
    noop: void,
    cancel: CancelError!void,
    accept: AcceptError!posix.socket_t,
    connect: ConnectError!void,
    poll: PollError!void,
    read: ReadError!usize,
    pread: ReadError!usize,
    write: WriteError!usize,
    pwrite: WriteError!usize,
    send: WriteError!usize,
    recv: ReadError!usize,
    sendmsg: WriteError!usize,
    recvmsg: ReadError!usize,
    close: CloseError!void,
    shutdown: ShutdownError!void,
    timer: TimerError!TimerTrigger,
};

/// All the supported operations of this event loop. These are always
/// backend-specific and therefore the structure and types change depending
/// on the underlying system in use. The high level operations are
/// done by initializing the request handles.
pub const Operation = union(OperationType) {
    noop: void,

    cancel: struct {
        c: *Completion,
    },

    accept: struct {
        socket: posix.socket_t,
        addr: posix.sockaddr = undefined,
        addr_size: posix.socklen_t = @sizeOf(posix.sockaddr),
        flags: u32 = posix.SOCK.CLOEXEC,
    },

    connect: struct {
        socket: posix.socket_t,
        addr: net.Address,
    },

    /// Poll for events but do not perform any operations on them being
    /// ready. The "events" field are a OR-ed list of EPOLL events.
    poll: struct {
        fd: posix.fd_t,
        events: u32,
    },

    read: struct {
        fd: posix.fd_t,
        buffer: ReadBuffer,
    },

    pread: struct {
        fd: posix.fd_t,
        buffer: ReadBuffer,
        offset: u64,
    },

    write: struct {
        fd: posix.fd_t,
        buffer: WriteBuffer,
    },

    pwrite: struct {
        fd: posix.fd_t,
        buffer: WriteBuffer,
        offset: u64,
    },

    send: struct {
        fd: posix.fd_t,
        buffer: WriteBuffer,
    },

    recv: struct {
        fd: posix.fd_t,
        buffer: ReadBuffer,
    },

    sendmsg: struct {
        fd: posix.fd_t,
        msghdr: *linux.msghdr_const,

        /// Optionally, a write buffer can be specified and the given
        /// msghdr will be populated with information about this buffer.
        buffer: ?WriteBuffer = null,

        /// Do not use this, it is only used internally.
        iov: [1]posix.iovec_const = undefined,
    },

    recvmsg: struct {
        fd: posix.fd_t,
        msghdr: *linux.msghdr,
    },

    close: struct {
        fd: posix.fd_t,
    },

    shutdown: struct {
        socket: posix.socket_t,
        how: ShutdownHow = .both,
    },

    timer: Timer,

    const Timer = struct {
        /// The absolute time to fire this timer next.
        next: std.os.linux.timespec,

        /// Only used internally. If this is non-null and timer is
        /// CANCELLED, then the timer is rearmed automatically with this
        /// as the next time. The callback will not be called on the
        /// cancellation.
        reset: ?std.os.linux.timespec = null,

        /// Internal heap fields.
        heap: heap.IntrusiveField(Timer) = .{},

        /// We point back to completion for now. When issue[1] is fixed,
        /// we can juse use that from our heap fields.
        /// [1]: https://github.com/ziglang/zig/issues/6611
        c: *Completion = undefined,

        fn less(_: void, a: *const Timer, b: *const Timer) bool {
            return a.ns() < b.ns();
        }

        /// Returns the nanoseconds of this timer. Note that maxInt(u64) ns is
        /// 584 years so if we get any overflows we just use maxInt(u64). If
        /// any software is running in 584 years waiting on this timer...
        /// shame on me I guess... but I'll be dead.
        fn ns(self: *const Timer) u64 {
            assert(self.next.sec >= 0);
            assert(self.next.nsec >= 0);

            const max = std.math.maxInt(u64);
            const s_ns = std.math.mul(
                u64,
                @as(u64, @intCast(self.next.sec)),
                std.time.ns_per_s,
            ) catch return max;
            return std.math.add(u64, s_ns, @as(u64, @intCast(self.next.nsec))) catch
                return max;
        }
    };
};

/// ReadBuffer are the various options for reading.
pub const ReadBuffer = union(enum) {
    /// Read into this slice.
    slice: []u8,

    /// Read into this array, just set this to undefined and it will
    /// be populated up to the size of the array. This is an option because
    /// the other union members force a specific size anyways so this lets us
    /// use the other size in the union to support small reads without worrying
    /// about buffer allocation.
    ///
    /// To know the size read you have to use the return value of the
    /// read operations (i.e. recv).
    ///
    /// Note that the union at the time of this writing could accomodate a
    /// much larger fixed size array here but we want to retain flexiblity
    /// for future fields.
    array: [32]u8,

    // TODO: future will have vectors
};

/// WriteBuffer are the various options for writing.
pub const WriteBuffer = union(enum) {
    /// Write from this buffer.
    slice: []const u8,

    /// Write from this array. See ReadBuffer.array for why we support this.
    array: struct {
        array: [32]u8,
        len: usize,
    },

    // TODO: future will have vectors
};

const ThreadPoolError = error{
    ThreadPoolRequired,
    ThreadPoolUnsupported,
};

pub const CancelError = ThreadPoolError || error{
    NotFound,
};

pub const ShutdownHow = std.Io.net.ShutdownHow;

pub const EpollCtlError = error{
    FileDescriptorAlreadyPresentInSet,
    OperationCausesCircularLoop,
    FileDescriptorNotRegistered,
    SystemResources,
    UserResourceLimitReached,
    FileDescriptorIncompatibleWithEpoll,
} || posix.UnexpectedError;

pub const PosixShutdownError = error{
    ConnectionAborted,
    ConnectionResetByPeer,
    BlockingOperationInProgress,
    NetworkSubsystemFailed,
    SocketNotConnected,
    SystemResources,
} || posix.UnexpectedError;

pub const AcceptError = EpollCtlError || error{
    DupFailed,
    Unknown,
};

pub const CloseError = EpollCtlError || ThreadPoolError || error{
    Unknown,
};

pub const PollError = EpollCtlError || error{
    DupFailed,
    Unknown,
};

pub const ShutdownError = EpollCtlError || PosixShutdownError || error{
    Unknown,
};

pub const ConnectError = EpollCtlError || std.Io.net.IpAddress.ConnectError || xev_posix.ConnectError || error{
    DupFailed,
    Unknown,
};

pub const ReadError = ThreadPoolError || EpollCtlError ||
    xev_posix.ReadError ||
    xev_posix.PReadError ||
    xev_posix.RecvFromError ||
    error{
        DupFailed,
        EOF,
        Unknown,
    };

pub const WriteError = ThreadPoolError || EpollCtlError ||
    xev_posix.WriteError ||
    xev_posix.PWriteError ||
    xev_posix.SendError ||
    error{
        DupFailed,
        Unknown,
    };

pub const TimerError = error{
    Unexpected,
};

pub const TimerTrigger = enum {
    /// Unused with epoll
    request,

    /// Timer expired.
    expiration,

    /// Timer was canceled.
    cancel,
};

test "Completion size" {
    const testing = std.testing;

    // Just so we are aware when we change the size
    try testing.expectEqual(@as(usize, 184), @sizeOf(Completion));
}

test "epoll: default completion" {
    const testing = std.testing;

    var loop = try Loop.init(.{});
    defer loop.deinit();

    var c: Completion = .{};
    loop.add(&c);

    // Tick
    try loop.run(.until_done);

    // Completion should be dead.
    try testing.expect(c.state() == .dead);
}

test "epoll: loop time" {
    const testing = std.testing;

    var loop = try Loop.init(.{});
    defer loop.deinit();

    // should never init zero
    const now = loop.now();
    try testing.expect(now > 0);

    // should update on a loop tick
    while (now == loop.now()) try loop.run(.no_wait);
}

test "epoll: stop" {
    const testing = std.testing;

    var loop = try Loop.init(.{});
    defer loop.deinit();

    // Add the timer
    var called = false;
    var c1: Completion = undefined;
    loop.timer(&c1, 1_000_000, &called, (struct {
        fn callback(ud: ?*anyopaque, l: *Loop, _: *Completion, r: Result) CallbackAction {
            _ = l;
            _ = r;
            const b = @as(*bool, @ptrCast(ud.?));
            b.* = true;
            return .disarm;
        }
    }).callback);

    // Tick
    try loop.run(.no_wait);
    try testing.expect(!called);

    // Stop
    loop.stop();
    try loop.run(.until_done);
    try testing.expect(!called);
}

test "epoll: timer" {
    const testing = std.testing;

    var loop = try Loop.init(.{});
    defer loop.deinit();

    // Add the timer
    var called = false;
    var c1: Completion = undefined;
    loop.timer(&c1, 1, &called, (struct {
        fn callback(
            ud: ?*anyopaque,
            l: *Loop,
            _: *Completion,
            r: Result,
        ) CallbackAction {
            _ = l;
            _ = r;
            const b = @as(*bool, @ptrCast(ud.?));
            b.* = true;
            return .disarm;
        }
    }).callback);

    // Add another timer
    var called2 = false;
    var c2: Completion = undefined;
    loop.timer(&c2, 100_000, &called2, (struct {
        fn callback(
            ud: ?*anyopaque,
            l: *Loop,
            _: *Completion,
            r: Result,
        ) CallbackAction {
            _ = l;
            _ = r;
            const b = @as(*bool, @ptrCast(ud.?));
            b.* = true;
            return .disarm;
        }
    }).callback);

    // State checking
    try testing.expect(c1.state() == .active);
    try testing.expect(c2.state() == .active);

    // Tick
    while (!called) try loop.run(.no_wait);
    try testing.expect(called);
    try testing.expect(!called2);

    // State checking
    try testing.expect(c1.state() == .dead);
    try testing.expect(c2.state() == .active);
}

test "epoll: timer reset" {
    const testing = std.testing;

    var loop = try Loop.init(.{});
    defer loop.deinit();

    const cb: Callback = (struct {
        fn callback(
            ud: ?*anyopaque,
            l: *Loop,
            _: *Completion,
            r: Result,
        ) CallbackAction {
            _ = l;
            const v = @as(*?TimerTrigger, @ptrCast(ud.?));
            v.* = r.timer catch unreachable;
            return .disarm;
        }
    }).callback;

    // Add the timer
    var trigger: ?TimerTrigger = null;
    var c1: Completion = undefined;
    loop.timer(&c1, 100_000, &trigger, cb);

    // We know timer won't be called from the timer test previously.
    try loop.run(.no_wait);
    try testing.expect(trigger == null);

    // Reset the timer
    var c_cancel: Completion = .{};
    loop.timer_reset(&c1, &c_cancel, 1, &trigger, cb);
    try testing.expect(c1.state() == .active);
    try testing.expect(c_cancel.state() == .active);

    // Run
    try loop.run(.until_done);
    try testing.expect(trigger.? == .expiration);
    try testing.expect(c1.state() == .dead);
    try testing.expect(c_cancel.state() == .dead);
}

test "epoll: timer reset before tick" {
    const testing = std.testing;

    var loop = try Loop.init(.{});
    defer loop.deinit();

    const cb: Callback = (struct {
        fn callback(
            ud: ?*anyopaque,
            l: *Loop,
            _: *Completion,
            r: Result,
        ) CallbackAction {
            _ = l;
            const v = @as(*?TimerTrigger, @ptrCast(ud.?));
            v.* = r.timer catch unreachable;
            return .disarm;
        }
    }).callback;

    // Add the timer
    var trigger: ?TimerTrigger = null;
    var c1: Completion = undefined;
    loop.timer(&c1, 100_000, &trigger, cb);

    // Reset the timer
    var c_cancel: Completion = .{};
    loop.timer_reset(&c1, &c_cancel, 1, &trigger, cb);
    try testing.expect(c1.state() == .active);
    try testing.expect(c_cancel.state() == .dead);

    // Run
    try loop.run(.until_done);
    try testing.expect(trigger.? == .expiration);
    try testing.expect(c1.state() == .dead);
    try testing.expect(c_cancel.state() == .dead);
}

test "epoll: timer reset after trigger" {
    const testing = std.testing;

    var loop = try Loop.init(.{});
    defer loop.deinit();

    const cb: Callback = (struct {
        fn callback(
            ud: ?*anyopaque,
            l: *Loop,
            _: *Completion,
            r: Result,
        ) CallbackAction {
            _ = l;
            const v = @as(*?TimerTrigger, @ptrCast(ud.?));
            v.* = r.timer catch unreachable;
            return .disarm;
        }
    }).callback;

    // Add the timer
    var trigger: ?TimerTrigger = null;
    var c1: Completion = undefined;
    loop.timer(&c1, 1, &trigger, cb);

    // Run the timer
    try loop.run(.until_done);
    try testing.expect(trigger.? == .expiration);
    try testing.expect(c1.state() == .dead);
    trigger = null;

    // Reset the timer
    var c_cancel: Completion = .{};
    loop.timer_reset(&c1, &c_cancel, 1, &trigger, cb);
    try testing.expect(c1.state() == .active);
    try testing.expect(c_cancel.state() == .dead);

    // Run
    try loop.run(.until_done);
    try testing.expect(trigger.? == .expiration);
    try testing.expect(c1.state() == .dead);
    try testing.expect(c_cancel.state() == .dead);
}

test "epoll: timerfd" {
    const testing = std.testing;

    var loop = try Loop.init(.{});
    defer loop.deinit();

    // We'll try with a simple timerfd
    const Timerfd = @import("../linux/timerfd.zig").Timerfd;
    var t = try Timerfd.init(.MONOTONIC, .{});
    defer t.deinit();
    try t.set(.{}, &.{ .value = .{ .nanoseconds = 1 } }, null);

    // Add the timer
    var called = false;
    var c: Completion = .{
        .op = .{
            .read = .{
                .fd = t.fd,
                .buffer = .{ .array = undefined },
            },
        },

        .userdata = &called,
        .callback = (struct {
            fn callback(
                ud: ?*anyopaque,
                l: *Loop,
                c: *Completion,
                r: Result,
            ) CallbackAction {
                _ = r.read catch unreachable;
                _ = c;
                _ = l;
                const b = @as(*bool, @ptrCast(ud.?));
                b.* = true;
                return .disarm;
            }
        }).callback,
    };
    loop.add(&c);

    // Tick
    try loop.run(.until_done);
    try testing.expect(called);
}

test "epoll: socket accept/connect/send/recv/close" {
    const mem = std.mem;
    const os = posix;
    const testing = std.testing;

    var loop = try Loop.init(.{});
    defer loop.deinit();

    // Create a TCP server socket
    const address = try net.Address.parseIp4("127.0.0.1", 3131);
    const kernel_backlog = 1;
    var ln = try xev_posix.socket(address.any.family, os.SOCK.STREAM | os.SOCK.CLOEXEC, 0);
    errdefer xev_posix.close(ln);
    try os.setsockopt(ln, os.SOL.SOCKET, os.SO.REUSEADDR, &mem.toBytes(@as(c_int, 1)));
    try xev_posix.bind(ln, &address.any, address.getOsSockLen());
    try xev_posix.listen(ln, kernel_backlog);

    // Create a TCP client socket
    var client_conn = try xev_posix.socket(
        address.any.family,
        os.SOCK.NONBLOCK | os.SOCK.STREAM | os.SOCK.CLOEXEC,
        0,
    );
    errdefer xev_posix.close(client_conn);

    // Accept
    var server_conn: os.socket_t = 0;
    var c_accept: Completion = .{
        .op = .{
            .accept = .{
                .socket = ln,
            },
        },

        .userdata = &server_conn,
        .callback = (struct {
            fn callback(
                ud: ?*anyopaque,
                l: *Loop,
                c: *Completion,
                r: Result,
            ) CallbackAction {
                _ = l;
                _ = c;
                const conn = @as(*os.socket_t, @ptrCast(@alignCast(ud.?)));
                conn.* = r.accept catch unreachable;
                return .disarm;
            }
        }).callback,
    };
    loop.add(&c_accept);

    // Connect
    var connected = false;
    var c_connect: Completion = .{
        .op = .{
            .connect = .{
                .socket = client_conn,
                .addr = address,
            },
        },

        .userdata = &connected,
        .callback = (struct {
            fn callback(
                ud: ?*anyopaque,
                l: *Loop,
                c: *Completion,
                r: Result,
            ) CallbackAction {
                _ = l;
                _ = c;
                _ = r.connect catch unreachable;
                const b = @as(*bool, @ptrCast(ud.?));
                b.* = true;
                return .disarm;
            }
        }).callback,
    };
    loop.add(&c_connect);

    // Wait for the connection to be established
    try loop.run(.until_done);
    try testing.expect(server_conn > 0);
    try testing.expect(connected);

    // Send
    var c_send: Completion = .{
        .op = .{
            .send = .{
                .fd = client_conn,
                .buffer = .{ .slice = &[_]u8{ 1, 1, 2, 3, 5, 8, 13 } },
            },
        },

        .callback = (struct {
            fn callback(
                ud: ?*anyopaque,
                l: *Loop,
                c: *Completion,
                r: Result,
            ) CallbackAction {
                _ = l;
                _ = c;
                _ = r.send catch unreachable;
                _ = ud;
                return .disarm;
            }
        }).callback,
    };
    loop.add(&c_send);

    // Receive
    var recv_buf: [128]u8 = undefined;
    var recv_len: usize = 0;
    var c_recv: Completion = .{
        .op = .{
            .recv = .{
                .fd = server_conn,
                .buffer = .{ .slice = &recv_buf },
            },
        },

        .userdata = &recv_len,
        .callback = (struct {
            fn callback(
                ud: ?*anyopaque,
                l: *Loop,
                c: *Completion,
                r: Result,
            ) CallbackAction {
                _ = l;
                _ = c;
                const ptr = @as(*usize, @ptrCast(@alignCast(ud.?)));
                ptr.* = r.recv catch unreachable;
                return .disarm;
            }
        }).callback,
    };
    loop.add(&c_recv);

    // Wait for the send/receive
    try loop.run(.until_done);
    try testing.expectEqualSlices(u8, c_send.op.send.buffer.slice, recv_buf[0..recv_len]);

    // Shutdown
    var shutdown = false;
    var c_client_shutdown: Completion = .{
        .op = .{
            .shutdown = .{
                .socket = client_conn,
            },
        },

        .userdata = &shutdown,
        .callback = (struct {
            fn callback(
                ud: ?*anyopaque,
                l: *Loop,
                c: *Completion,
                r: Result,
            ) CallbackAction {
                _ = l;
                _ = c;
                _ = r.shutdown catch unreachable;
                const ptr = @as(*bool, @ptrCast(@alignCast(ud.?)));
                ptr.* = true;
                return .disarm;
            }
        }).callback,
    };
    loop.add(&c_client_shutdown);
    try loop.run(.until_done);
    try testing.expect(shutdown);

    // Read should be EOF
    var eof: ?bool = null;
    c_recv = .{
        .op = .{
            .recv = .{
                .fd = server_conn,
                .buffer = .{ .slice = &recv_buf },
            },
        },

        .userdata = &eof,
        .callback = (struct {
            fn callback(
                ud: ?*anyopaque,
                l: *Loop,
                c: *Completion,
                r: Result,
            ) CallbackAction {
                _ = l;
                _ = c;
                const ptr = @as(*?bool, @ptrCast(@alignCast(ud.?)));
                ptr.* = if (r.recv) |_| false else |err| switch (err) {
                    error.EOF => true,
                    else => false,
                };
                return .disarm;
            }
        }).callback,
    };
    loop.add(&c_recv);

    try loop.run(.until_done);
    try testing.expect(eof.? == true);

    // Close
    var c_client_close: Completion = .{
        .op = .{
            .close = .{
                .fd = client_conn,
            },
        },

        .userdata = &client_conn,
        .callback = (struct {
            fn callback(
                ud: ?*anyopaque,
                l: *Loop,
                c: *Completion,
                r: Result,
            ) CallbackAction {
                _ = l;
                _ = c;
                _ = r.close catch unreachable;
                const ptr = @as(*os.socket_t, @ptrCast(@alignCast(ud.?)));
                ptr.* = 0;
                return .disarm;
            }
        }).callback,
    };
    loop.add(&c_client_close);

    var c_server_close: Completion = .{
        .op = .{
            .close = .{
                .fd = ln,
            },
        },

        .userdata = &ln,
        .callback = (struct {
            fn callback(
                ud: ?*anyopaque,
                l: *Loop,
                c: *Completion,
                r: Result,
            ) CallbackAction {
                _ = l;
                _ = c;
                _ = r.close catch unreachable;
                const ptr = @as(*os.socket_t, @ptrCast(@alignCast(ud.?)));
                ptr.* = 0;
                return .disarm;
            }
        }).callback,
    };
    loop.add(&c_server_close);

    // Wait for the sockets to close
    try loop.run(.until_done);
    try testing.expect(ln == 0);
    try testing.expect(client_conn == 0);
}

test "epoll: timer cancellation" {
    const testing = std.testing;

    var loop = try Loop.init(.{});
    defer loop.deinit();

    // Add the timer
    var trigger: ?TimerTrigger = null;
    var c1: Completion = undefined;
    loop.timer(&c1, 100_000, &trigger, (struct {
        fn callback(
            ud: ?*anyopaque,
            l: *Loop,
            _: *Completion,
            r: Result,
        ) CallbackAction {
            _ = l;
            const ptr = @as(*?TimerTrigger, @ptrCast(@alignCast(ud.?)));
            ptr.* = r.timer catch unreachable;
            return .disarm;
        }
    }).callback);

    // Tick and verify we're not called.
    try loop.run(.no_wait);
    try testing.expect(trigger == null);

    // Cancel the timer
    var called = false;
    var c_cancel: Completion = .{
        .op = .{
            .cancel = .{
                .c = &c1,
            },
        },

        .userdata = &called,
        .callback = (struct {
            fn callback(
                ud: ?*anyopaque,
                l: *Loop,
                c: *Completion,
                r: Result,
            ) CallbackAction {
                _ = l;
                _ = c;
                _ = r.cancel catch unreachable;
                const ptr = @as(*bool, @ptrCast(@alignCast(ud.?)));
                ptr.* = true;
                return .disarm;
            }
        }).callback,
    };
    loop.add(&c_cancel);

    // Tick
    try loop.run(.until_done);
    try testing.expect(called);
    try testing.expect(trigger.? == .cancel);
}

test "epoll: canceling a completed operation" {
    const testing = std.testing;

    var loop = try Loop.init(.{});
    defer loop.deinit();

    // Add the timer
    var trigger: ?TimerTrigger = null;
    var c1: Completion = undefined;
    loop.timer(&c1, 1, &trigger, (struct {
        fn callback(
            ud: ?*anyopaque,
            l: *Loop,
            _: *Completion,
            r: Result,
        ) CallbackAction {
            _ = l;
            const ptr = @as(*?TimerTrigger, @ptrCast(@alignCast(ud.?)));
            ptr.* = r.timer catch unreachable;
            return .disarm;
        }
    }).callback);

    // Tick and verify we're not called.
    try loop.run(.until_done);
    try testing.expect(trigger.? == .expiration);

    // Cancel the timer
    var called = false;
    var c_cancel: Completion = .{
        .op = .{
            .cancel = .{
                .c = &c1,
            },
        },

        .userdata = &called,
        .callback = (struct {
            fn callback(
                ud: ?*anyopaque,
                l: *Loop,
                c: *Completion,
                r: Result,
            ) CallbackAction {
                _ = l;
                _ = c;
                _ = r.cancel catch unreachable;
                const ptr = @as(*bool, @ptrCast(@alignCast(ud.?)));
                ptr.* = true;
                return .disarm;
            }
        }).callback,
    };
    loop.add(&c_cancel);

    // Tick
    try loop.run(.until_done);
    try testing.expect(called);
    try testing.expect(trigger.? == .expiration);
}