oscall 0.1.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
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
//! The poller on Windows: an I/O completion port, fed by `IOCTL_AFD_POLL`.
//!
//! Windows has no call that waits for the readiness of many sockets at a
//! cost that does not grow with their number, but the driver behind
//! Winsock (AFD, the *ancillary function driver*) has an operation that
//! completes when a socket becomes ready: `IOCTL_AFD_POLL`, which is what
//! `select` and `WSAPoll` are made of. Issued asynchronously on a handle
//! bound to a completion port, one for each registered socket, it turns the
//! port into a readiness queue. This is the technique of `wepoll`, which
//! libuv and mio use too; the structures and constants are those of
//! `wepoll`'s `afd.h`.
//!
//! How it is put together:
//!
//! - Operations are issued on *helper* handles (`\Device\Afd\...`, opened
//!   with `NtCreateFile` and bound to the port), not on the sockets: the
//!   sockets are left alone, and can be bound to a port of the caller's.
//!   A helper serves a limited number of sockets, since cancelling an
//!   operation searches those of its handle.
//! - A registration is a heap allocation that holds the operation's status
//!   block and its poll buffer, which the system writes when the operation
//!   completes. Its address travels with the operation and comes back in
//!   the completion packet. **It is freed only once no operation is in
//!   flight**: a registration removed meanwhile is marked, its operation
//!   cancelled, and its memory released when the packet is taken from the
//!   port. If the poller is dropped first, the operations are cancelled and
//!   the port drained; what does not come back in time is leaked, never
//!   freed.
//! - An operation completes once. For a level-triggered registration it is
//!   issued again by the next wait (not at once: the caller has not read
//!   yet, and the answer would be stale by the time it is collected); for a
//!   one-shot registration, when `modify` arms it again.
//! - An operation cannot be changed: when a registration wants more than
//!   its operation watches, the operation is cancelled, and issued again
//!   when its (cancelled) completion is collected.
//! - A socket closed while an operation watches it completes the operation
//!   with `AFD_POLL_LOCAL_CLOSE`: the registration is then dropped. With no
//!   operation in flight the closing goes unnoticed until the next one is
//!   issued, on what may be another socket by then, and the registration
//!   stands in the way of registering a socket of the same number: hence
//!   the rule to deregister before closing.
//!
//! Everything but the two kernel-written blocks of a registration is
//! guarded by one lock, which is not held while waiting on the port.
//!
//! # What is not a socket
//!
//! The port also receives packets that are no operation's, told apart by
//! their completion key. Nothing of them is written by the system into
//! memory of the poller: a packet carries two numbers, and one that comes
//! for something that is gone names nothing and is dropped.
//!
//! - **Waitable handles** (a child process is one): a *wait completion
//!   packet* (`NtCreateWaitCompletionPacket`,
//!   `NtAssociateWaitCompletionPacket`, Windows 8 and later: what the
//!   thread pool's waits and the runtimes of Go and .NET are made of) is a
//!   kernel object that queues a packet of the caller's choosing to a port
//!   when a handle is signaled, once. The packet says a *cookie*, a number
//!   given to one association and never again, which the table of the
//!   poller turns into a token: a packet in flight for a handle that was
//!   deregistered or armed again has a cookie the table no longer knows.
//! - **Console control events**: the handler of `process::Signals`, on the
//!   thread the system runs it on, posts a packet with the cookie of each
//!   poller that registered the subscription. The ports to post to are in
//!   a list of the process, whose lock the handler holds while it posts:
//!   deregistering, and dropping the poller or the subscription, take the
//!   port out of the list under that lock, so that no handler posts to a
//!   port afterwards, and none to one that is closed.
//! - **Timers**: one waitable timer for the poller, armed for the earliest
//!   deadline of the queue of timers and waited for by a wait completion
//!   packet. Its packet says nothing but "look at the queue".

use alloc::boxed::Box;
use alloc::collections::BTreeMap;
use alloc::vec::Vec;
use core::cell::{Cell, UnsafeCell};
use core::ffi::c_void;
use core::ptr::{null, null_mut};
use core::sync::atomic::{AtomicBool, Ordering};
use core::time::Duration;

use crate::event::lock::Lock;
use crate::event::timers::{Op, Timers};
use crate::event::{Interest, ModeKind, Readiness};
use crate::sys::RawHandle;
use crate::sys::io::OverlappedEntry;
use crate::sys::net::RawSocket;
use crate::sys::time::{to_units, unbiased};
use crate::sys::{dll, last_error};
use crate::{Error, ErrorKind, Result};

// The events of `IOCTL_AFD_POLL`.
const AFD_POLL_RECEIVE: u32 = 0x0001;
const AFD_POLL_SEND: u32 = 0x0004;
const AFD_POLL_DISCONNECT: u32 = 0x0008;
const AFD_POLL_ABORT: u32 = 0x0010;
const AFD_POLL_LOCAL_CLOSE: u32 = 0x0020;
const AFD_POLL_ACCEPT: u32 = 0x0080;
const AFD_POLL_CONNECT_FAIL: u32 = 0x0100;

const IOCTL_AFD_POLL: u32 = 0x0001_2024;

const STATUS_SUCCESS: i32 = 0;
const STATUS_PENDING: i32 = 0x0000_0103;
const STATUS_INVALID_HANDLE: i32 = 0xC000_0008_u32 as i32;
const STATUS_OBJECT_TYPE_MISMATCH: i32 = 0xC000_0024_u32 as i32;
const STATUS_CANCELLED: i32 = 0xC000_0120_u32 as i32;
const STATUS_NOT_FOUND: i32 = 0xC000_0225_u32 as i32;

const SYNCHRONIZE: u32 = 0x0010_0000;
const FILE_SHARE_READ: u32 = 1;
const FILE_SHARE_WRITE: u32 = 2;
/// The create disposition: open what exists.
const FILE_OPEN: u32 = 1;
const FILE_SKIP_SET_EVENT_ON_HANDLE: u8 = 2;
const INVALID_HANDLE_VALUE: *mut c_void = usize::MAX as *mut c_void;

const SIO_BSP_HANDLE: u32 = 0x4800_001B;
const SIO_BSP_HANDLE_SELECT: u32 = 0x4800_001C;
const SIO_BSP_HANDLE_POLL: u32 = 0x4800_001D;
const SIO_BASE_HANDLE: u32 = 0x4800_0022;

const WAIT_TIMEOUT: i32 = 258;
const INFINITE: u32 = u32::MAX;
/// The interrupt time counts in units of 100 ns.
const UNITS_PER_MS: u64 = 10_000;

const GENERIC_ALL: u32 = 0x1000_0000;
const CREATE_WAITABLE_TIMER_HIGH_RESOLUTION: u32 = 2;
const TIMER_ALL_ACCESS: u32 = 0x1F0003;

/// The completion key of the operations on the helper handles, and of the
/// packet of `wake`, which has no overlapped structure.
const KEY_SOCKET: usize = 0;
/// The completion key of the packets of handles and of console control
/// events: their "overlapped structure" is a cookie.
const KEY_SOURCE: usize = 1;
/// The completion key of the packet of the poller's timer.
const KEY_TIMER: usize = 2;

/// The longest the timer is armed for at once, in units of 100 ns: a day.
/// It is armed again when it fires with nothing due.
const MAX_TIMER_UNITS: u64 = 86_400 * 10_000_000;

/// How many sockets one helper handle serves.
const HELPER_USERS: usize = 32;
/// How many completions one call takes from the port.
const BATCH: usize = 64;
/// How long `drop` waits for cancelled operations to come back, each time,
/// and how many times in a row it accepts that nothing does.
const DRAIN_MILLISECONDS: u32 = 100;
const DRAIN_PATIENCE: u32 = 20;

/// The device the helper handles are opened on. The name after `Afd\` is
/// free.
const HELPER_NAME: &[u8] = b"\\Device\\Afd\\oscall";
static HELPER_NAME_WIDE: [u16; HELPER_NAME.len()] = {
    let mut wide = [0; HELPER_NAME.len()];
    let mut i = 0;
    while i < wide.len() {
        wide[i] = HELPER_NAME[i] as u16;
        i += 1;
    }
    wide
};

/// `IO_STATUS_BLOCK`. Its first member is a union of the status and a
/// pointer: pointer-sized, with the status in its low 32 bits.
#[repr(C)]
struct IoStatusBlock {
    status: usize,
    information: usize,
}

/// `AFD_POLL_HANDLE_INFO`.
#[repr(C)]
struct AfdPollHandleInfo {
    handle: *mut c_void,
    events: u32,
    status: i32,
}

/// `AFD_POLL_INFO`, for one handle.
#[repr(C)]
struct AfdPollInfo {
    timeout: i64,
    count: u32,
    exclusive: u32,
    handle: AfdPollHandleInfo,
}

/// `UNICODE_STRING`.
#[repr(C)]
struct UnicodeString {
    /// In bytes.
    length: u16,
    maximum_length: u16,
    buffer: *const u16,
}

/// `OBJECT_ATTRIBUTES`.
#[repr(C)]
struct ObjectAttributes {
    length: u32,
    root_directory: *mut c_void,
    object_name: *const UnicodeString,
    attributes: u32,
    security_descriptor: *const c_void,
    security_quality_of_service: *const c_void,
}

const _: () = {
    assert!(size_of::<AfdPollInfo>() == 32);
    assert!(size_of::<IoStatusBlock>() == 2 * size_of::<usize>());
};

dll!("ntdll.dll" {
    fn NtCreateFile(
        handle: *mut *mut c_void,
        access: u32,
        attributes: *const ObjectAttributes,
        status: *mut IoStatusBlock,
        allocation_size: *const i64,
        file_attributes: u32,
        share: u32,
        disposition: u32,
        options: u32,
        ea: *const c_void,
        ea_length: u32,
    ) -> i32;
    fn NtDeviceIoControlFile(
        file: *mut c_void,
        event: *mut c_void,
        apc_routine: *const c_void,
        apc_context: *const c_void,
        status: *mut IoStatusBlock,
        code: u32,
        input: *const c_void,
        input_length: u32,
        output: *mut c_void,
        output_length: u32,
    ) -> i32;
    fn NtCancelIoFileEx(
        file: *mut c_void,
        request: *const IoStatusBlock,
        status: *mut IoStatusBlock,
    ) -> i32;
    fn RtlNtStatusToDosError(status: i32) -> u32;
    fn NtCreateWaitCompletionPacket(
        packet: *mut *mut c_void,
        access: u32,
        attributes: *const ObjectAttributes,
    ) -> i32;
    fn NtAssociateWaitCompletionPacket(
        packet: *mut c_void,
        port: *mut c_void,
        target: *mut c_void,
        key: *const c_void,
        context: *const c_void,
        status: i32,
        information: usize,
        already_signaled: *mut u8,
    ) -> i32;
    fn NtCancelWaitCompletionPacket(packet: *mut c_void, remove_signaled: u8) -> i32;
});

dll!("kernel32.dll" {
    fn CreateIoCompletionPort(
        file: *mut c_void,
        port: *mut c_void,
        key: usize,
        threads: u32,
    ) -> *mut c_void;
    fn GetQueuedCompletionStatusEx(
        port: *mut c_void,
        entries: *mut OverlappedEntry,
        count: u32,
        removed: *mut u32,
        milliseconds: u32,
        alertable: i32,
    ) -> i32;
    fn PostQueuedCompletionStatus(
        port: *mut c_void,
        bytes: u32,
        key: usize,
        overlapped: *const c_void,
    ) -> i32;
    fn SetFileCompletionNotificationModes(file: *mut c_void, flags: u8) -> i32;
    fn CloseHandle(handle: *mut c_void) -> i32;
    fn CreateWaitableTimerExW(
        attributes: *const c_void,
        name: *const u16,
        flags: u32,
        access: u32,
    ) -> *mut c_void;
    fn SetWaitableTimer(
        timer: *mut c_void,
        due: *const i64,
        period: i32,
        routine: *const c_void,
        argument: *const c_void,
        resume: i32,
    ) -> i32;
    fn CancelWaitableTimer(timer: *mut c_void) -> i32;
});

dll!("ws2_32.dll" {
    fn WSAIoctl(
        socket: usize,
        code: u32,
        input: *const c_void,
        input_length: u32,
        output: *mut c_void,
        output_length: u32,
        returned: *mut u32,
        overlapped: *mut c_void,
        completion: *const c_void,
    ) -> i32;
    fn WSAGetLastError() -> i32;
});

/// The error of an `NTSTATUS`, as the Win32 code the rest of the crate
/// reports.
fn nt_error(status: i32) -> Error {
    // SAFETY: a pure function of its argument.
    Error::from_raw_os_error(unsafe { RtlNtStatusToDosError(status) } as i32)
}

/// Whether a status is an error (`NT_ERROR`), as opposed to a success, an
/// information or a warning. An asynchronous call that returns an error
/// has not started: no completion will come for it. With any other status
/// one will.
fn is_nt_error(status: i32) -> bool {
    status as u32 >= 0xC000_0000
}

/// The event of a poller: a completion translated.
#[derive(Clone, Copy)]
pub(crate) struct RawEvent {
    token: usize,
    readiness: Readiness,
    wake: bool,
    /// For a timer, how many times it expired; 0 for another event.
    expirations: u64,
}

impl RawEvent {
    pub(crate) const EMPTY: Self = Self {
        token: 0,
        readiness: Readiness::empty(),
        wake: false,
        expirations: 0,
    };

    pub(crate) fn is_timer(&self) -> bool {
        self.expirations != 0
    }

    pub(crate) fn expirations(&self) -> u64 {
        self.expirations
    }

    pub(crate) fn token(&self) -> usize {
        self.token
    }

    pub(crate) fn is_wake(&self) -> bool {
        self.wake
    }

    pub(crate) fn readiness(&self) -> Readiness {
        self.readiness
    }
}

/// What a registration asks `IOCTL_AFD_POLL` for. A connection that was
/// reset or could not be made is always asked for; the closing of the
/// socket is added to every operation.
fn afd_events(interest: Interest) -> u32 {
    let mut events = AFD_POLL_ABORT | AFD_POLL_CONNECT_FAIL;
    if interest.contains(Interest::READABLE) {
        events |= AFD_POLL_RECEIVE | AFD_POLL_ACCEPT | AFD_POLL_DISCONNECT;
    }
    if interest.contains(Interest::WRITABLE) {
        events |= AFD_POLL_SEND;
    }
    events
}

fn readiness(events: u32) -> Readiness {
    let mut readiness = Readiness::empty();
    for (bits, flags) in [
        (AFD_POLL_RECEIVE | AFD_POLL_ACCEPT, Readiness::READABLE),
        (AFD_POLL_SEND, Readiness::WRITABLE),
        // The peer shut down its sending side: the end of the stream is
        // there to read.
        (
            AFD_POLL_DISCONNECT,
            Readiness::READABLE.union(Readiness::READ_CLOSED),
        ),
        (AFD_POLL_ABORT, Readiness::HANGUP),
        (
            AFD_POLL_CONNECT_FAIL,
            Readiness::ERROR.union(Readiness::HANGUP),
        ),
    ] {
        if events & bits != 0 {
            readiness |= flags;
        }
    }
    readiness
}

/// The handle `IOCTL_AFD_POLL` wants: the socket of the base provider,
/// under whatever layered providers are installed.
fn base_socket(socket: RawSocket) -> Result<RawSocket> {
    let query = |code: u32| {
        let mut base: RawSocket = 0;
        let mut returned = 0;
        // SAFETY: the function writes one `SOCKET` to `base`, and the count
        // of bytes it wrote.
        let result = unsafe {
            WSAIoctl(
                socket,
                code,
                null(),
                0,
                (&raw mut base).cast(),
                size_of::<RawSocket>() as u32,
                &raw mut returned,
                null_mut(),
                null(),
            )
        };
        if result == 0 {
            Ok(base)
        } else {
            // SAFETY: WSAGetLastError only reads thread-local state.
            Err(Error::from_raw_os_error(unsafe { WSAGetLastError() }))
        }
    };
    let error = match query(SIO_BASE_HANDLE) {
        Ok(base) => return Ok(base),
        Err(error) => error,
    };
    // No provider should intercept that request, but some do. Then the
    // provider below is asked for, by the names it may know: an answer is
    // one only if it is another socket.
    for code in [SIO_BSP_HANDLE_SELECT, SIO_BSP_HANDLE_POLL, SIO_BSP_HANDLE] {
        if let Ok(base) = query(code)
            && base != socket
        {
            return Ok(base);
        }
    }
    Err(error)
}

/// Opens a helper handle and binds it to `port`.
fn open_helper(port: *mut c_void) -> Result<*mut c_void> {
    let name = UnicodeString {
        length: size_of_val(&HELPER_NAME_WIDE) as u16,
        maximum_length: size_of_val(&HELPER_NAME_WIDE) as u16,
        buffer: HELPER_NAME_WIDE.as_ptr(),
    };
    // No attribute: the handle is not inherited by child processes.
    let attributes = ObjectAttributes {
        length: size_of::<ObjectAttributes>() as u32,
        root_directory: null_mut(),
        object_name: &raw const name,
        attributes: 0,
        security_descriptor: null(),
        security_quality_of_service: null(),
    };
    let mut handle = INVALID_HANDLE_VALUE;
    let mut status = IoStatusBlock {
        status: 0,
        information: 0,
    };
    // SAFETY: the function reads the attributes and the name they point
    // to, and writes the handle and the status block. Without
    // `FILE_SYNCHRONOUS_IO_*` the handle is for asynchronous use.
    let result = unsafe {
        NtCreateFile(
            &raw mut handle,
            SYNCHRONIZE,
            &raw const attributes,
            &raw mut status,
            null(),
            0,
            FILE_SHARE_READ | FILE_SHARE_WRITE,
            FILE_OPEN,
            0,
            null(),
            0,
        )
    };
    if result < 0 {
        return Err(nt_error(result));
    }
    // SAFETY: both handles are open. With an existing port the function
    // binds the file to it, and returns the port.
    let bound = unsafe { CreateIoCompletionPort(handle, port, 0, 0) };
    // No event is wanted on the handle itself when an operation completes.
    // SAFETY: `handle` is open.
    if bound.is_null()
        || unsafe { SetFileCompletionNotificationModes(handle, FILE_SKIP_SET_EVENT_ON_HANDLE) } == 0
    {
        let error = last_error();
        // SAFETY: `handle` is open and not used again.
        unsafe { CloseHandle(handle) };
        return Err(error);
    }
    Ok(handle)
}

/// Creates a wait completion packet, associated with nothing.
fn create_packet() -> Result<*mut c_void> {
    let mut packet = null_mut();
    // SAFETY: the function writes the handle of the object it creates,
    // which is unnamed and not inherited.
    let status = unsafe { NtCreateWaitCompletionPacket(&raw mut packet, GENERIC_ALL, null()) };
    if status < 0 {
        return Err(nt_error(status));
    }
    Ok(packet)
}

/// Makes `packet`, which is associated with nothing, queue a packet with
/// `key` and `cookie` to `port` when `target` is signaled, at once if it
/// is. The wait is satisfied as a thread's would be.
fn associate(
    packet: *mut c_void,
    port: *mut c_void,
    target: *mut c_void,
    key: usize,
    cookie: usize,
) -> Result<()> {
    let mut already_signaled = 0u8;
    // SAFETY: the handles are open (a handle that is not is an error the
    // system reports); the key and the context are numbers, which the
    // system hands back and never follows; it writes one `BOOLEAN`.
    let status = unsafe {
        NtAssociateWaitCompletionPacket(
            packet,
            port,
            target,
            key as *const c_void,
            cookie as *const c_void,
            STATUS_SUCCESS,
            0,
            &raw mut already_signaled,
        )
    };
    if status < 0 {
        return Err(nt_error(status));
    }
    Ok(())
}

/// Ends the association of `packet`, and takes what it queued out of the
/// port if no wait has collected it. Returns whether the packet object can
/// be associated again: not when the system is queuing its packet at this
/// very moment (`STATUS_PENDING`), which then comes.
fn cancel_packet(packet: *mut c_void) -> bool {
    // SAFETY: `packet` is open.
    let status = unsafe { NtCancelWaitCompletionPacket(packet, 1) };
    // Cancelled: there was nothing to cancel.
    status == STATUS_SUCCESS || status == STATUS_CANCELLED
}

/// Ends the association of `packet` and closes it. A packet it queued and
/// that could not be taken back has a cookie nothing knows any more.
///
/// # Safety
///
/// `packet` must be an open wait completion packet, not used afterwards.
unsafe fn discard_packet(packet: *mut c_void) {
    cancel_packet(packet);
    // SAFETY: as the caller's.
    unsafe { CloseHandle(packet) };
}

/// A poller that is told of the console control events of a subscription.
struct Hook {
    /// The events of the subscription, which is what names it: bit `n` for
    /// event `n`. No two subscriptions share an event.
    set: u8,
    /// The completion port, as a number: open for as long as the hook is in
    /// the list.
    port: usize,
    cookie: usize,
}

/// The hooks of the process. The handler posts with the lock held, and a
/// port is taken out of the list before it is closed.
static HOOKS: Lock<Vec<Hook>> = Lock::new(Vec::new());

/// Called by the handler of console control events, on the thread the
/// system made for it, when it has recorded `event` for a subscription:
/// tells the pollers that registered the subscription.
pub(crate) fn signal_delivered(event: u32) {
    let hooks = HOOKS.lock();
    for hook in hooks.iter().filter(|hook| hook.set >> event & 1 != 0) {
        // SAFETY: the port is open while its hook is in the list, which
        // cannot change while the lock is held. Nothing can be done about
        // a failure: the event is recorded all the same.
        unsafe {
            PostQueuedCompletionStatus(
                hook.port as *mut c_void,
                0,
                KEY_SOURCE,
                hook.cookie as *const c_void,
            )
        };
    }
}

/// Called when the subscription to the events of `set` ends: no poller is
/// told of the events of the one that may follow.
pub(crate) fn signals_dropped(set: u8) {
    HOOKS.lock().retain(|hook| hook.set != set);
}

/// Where the poll operation of a registration is.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Status {
    /// None is in flight.
    Idle,
    /// One is in flight.
    Pending,
    /// One is in flight and was asked to stop.
    Cancelled,
}

/// What the system writes when an operation completes, at any time while
/// one is in flight: nothing here may be touched meanwhile.
struct Operation {
    status: IoStatusBlock,
    info: AfdPollInfo,
}

/// A registered socket. It lives on the heap at an address that does not
/// change, which is the context of its operations, and is only reached
/// through shared references, with the lock of the table held.
struct Registration {
    operation: UnsafeCell<Operation>,
    /// The socket it was registered as: its key in the table.
    socket: RawSocket,
    /// The base handle of the socket, which is what is polled.
    base: *mut c_void,
    /// The index of the helper handle its operations are issued on.
    helper: usize,
    token: Cell<usize>,
    /// The poll events the registration is interested in.
    wanted: Cell<u32>,
    oneshot: Cell<bool>,
    /// Cleared when a one-shot registration has fired.
    armed: Cell<bool>,
    status: Cell<Status>,
    /// The events the operation in flight watches.
    watched: Cell<u32>,
    /// No longer in the table: to free when its operation is over.
    retired: Cell<bool>,
    /// In the queue of registrations to update.
    queued: Cell<bool>,
}

struct Helper {
    handle: *mut c_void,
    /// How many registrations issue their operations on it.
    users: usize,
}

struct State {
    /// The registrations, by socket. Each is a `Box` turned into a pointer.
    registrations: BTreeMap<RawSocket, *mut Registration>,
    /// The sockets whose registration may need an operation started or
    /// cancelled. A socket no longer registered is skipped.
    queue: Vec<RawSocket>,
    helpers: Vec<Helper>,
    /// How many threads are waiting on the port: when there is one, an
    /// update cannot wait for the next wait.
    waiters: usize,
    /// How many operations are in flight, each with a registration that
    /// must not be freed.
    in_flight: usize,
    /// The handles that are registered, with the packet that waits for
    /// each.
    waits: BTreeMap<usize, Wait>,
    /// The subscriptions to console control events that are registered, by
    /// their set of events, with their cookie.
    signals: BTreeMap<u8, usize>,
    /// The token of each cookie that a packet may still bring.
    sources: BTreeMap<usize, usize>,
    /// The last cookie given.
    cookie: usize,
}

/// A registered handle.
struct Wait {
    /// The wait completion packet associated with the handle; null if it
    /// could not be made again when the registration was modified.
    packet: *mut c_void,
    /// What its packet says, which the association had for itself alone.
    cookie: usize,
}

/// The timers, and what fires for the earliest of them.
struct TimerState {
    timers: Timers,
    /// A waitable timer, created for the first timer; null before.
    timer: *mut c_void,
    /// The wait completion packet that waits for it; null when there is
    /// none to use again.
    packet: *mut c_void,
}

// SAFETY: the pointers are handles of kernel objects any thread may use.
unsafe impl Send for TimerState {}

// SAFETY: the pointers are to heap memory the state owns, and to kernel
// objects any thread may use.
unsafe impl Send for State {}

impl State {
    /// The index of a helper with room for a registration.
    fn helper(&mut self, port: *mut c_void) -> Result<usize> {
        if let Some(index) = self.helpers.iter().rposition(|h| h.users < HELPER_USERS) {
            return Ok(index);
        }
        self.helpers
            .try_reserve(1)
            .map_err(|_| ErrorKind::OutOfMemory)?;
        self.helpers.push(Helper {
            handle: open_helper(port)?,
            users: 0,
        });
        Ok(self.helpers.len() - 1)
    }

    /// A cookie no association had before. (They would come round after
    /// 2³² associations on a 32-bit system, where one that met a packet
    /// still in flight from then would make an event that is not true.)
    fn new_cookie(&mut self) -> usize {
        self.cookie = self.cookie.wrapping_add(1).max(1);
        self.cookie
    }

    /// Frees a registration.
    ///
    /// # Safety
    ///
    /// `ptr` must be a registration that is not in the table and has no
    /// operation in flight; it is not used afterwards.
    unsafe fn free(&mut self, ptr: *mut Registration) {
        // SAFETY: registrations are boxes, and this one is no longer
        // referenced by the table nor by the system.
        let registration = unsafe { Box::from_raw(ptr) };
        self.helpers[registration.helper].users -= 1;
    }

    /// Marks a registration as needing an update by the next `flush`.
    fn enqueue(&mut self, registration: &Registration) {
        if !registration.queued.replace(true) {
            self.queue.push(registration.socket);
        }
    }

    /// Updates every queued registration. An error is that of the last
    /// update that failed; the registration stays queued.
    fn flush(&mut self) -> Result<()> {
        let mut result = Ok(());
        let mut queue = core::mem::take(&mut self.queue);
        for &socket in &queue {
            let Some(&ptr) = self.registrations.get(&socket) else {
                continue;
            };
            // SAFETY: a registration in the table is allocated.
            unsafe { &*ptr }.queued.set(false);
            // SAFETY: `ptr` is in the table.
            if let Err(error) = unsafe { self.update(ptr) } {
                result = Err(error);
            }
        }
        // Keep the allocation, unless failed updates made another.
        queue.clear();
        if self.queue.is_empty() {
            self.queue = queue;
        }
        result
    }

    /// Makes the operation of a registration watch what the registration
    /// wants: starts one if none is in flight, cancels the one in flight if
    /// it watches too little (it is started again when its completion is
    /// collected).
    ///
    /// # Safety
    ///
    /// `ptr` must be a registration in the table.
    unsafe fn update(&mut self, ptr: *mut Registration) -> Result<()> {
        // SAFETY: a registration in the table is allocated.
        let registration = unsafe { &*ptr };
        if !registration.armed.get() {
            return Ok(());
        }
        let result = match registration.status.get() {
            Status::Cancelled => Ok(()),
            Status::Pending => {
                if registration.wanted.get() & !registration.watched.get() == 0 {
                    // What may complete for an event that is no longer
                    // wanted is sorted out then.
                    Ok(())
                } else {
                    self.cancel(registration)
                }
            }
            // SAFETY: as the caller's.
            Status::Idle => return unsafe { self.start(ptr) },
        };
        if result.is_err() {
            self.enqueue(registration);
        }
        result
    }

    /// Starts the operation of a registration that has none in flight.
    ///
    /// # Safety
    ///
    /// `ptr` must be a registration in the table, with no operation in
    /// flight.
    unsafe fn start(&mut self, ptr: *mut Registration) -> Result<()> {
        // SAFETY: a registration in the table is allocated.
        let registration = unsafe { &*ptr };
        let wanted = registration.wanted.get();
        let helper = self.helpers[registration.helper].handle;
        let operation = registration.operation.get();
        let size = size_of::<AfdPollInfo>() as u32;
        // SAFETY: no operation is in flight, so nothing else reads or
        // writes the blocks, which the call hands to the system until the
        // operation completes: the registration is not freed before. The
        // poll buffer is both the input and the output.
        let status = unsafe {
            (*operation).status = IoStatusBlock {
                status: STATUS_PENDING as usize,
                information: 0,
            };
            (*operation).info = AfdPollInfo {
                // Never: the operation ends when the socket is ready, or
                // when it is cancelled.
                timeout: i64::MAX,
                count: 1,
                exclusive: 0,
                handle: AfdPollHandleInfo {
                    handle: registration.base,
                    events: wanted | AFD_POLL_LOCAL_CLOSE,
                    status: 0,
                },
            };
            let info = (&raw mut (*operation).info).cast::<c_void>();
            NtDeviceIoControlFile(
                helper,
                null_mut(),
                null(),
                ptr.cast(),
                &raw mut (*operation).status,
                IOCTL_AFD_POLL,
                info,
                size,
                info,
                size,
            )
        };
        if !is_nt_error(status) {
            // Pending, or over already: either way a completion will come
            // through the port.
            registration.status.set(Status::Pending);
            registration.watched.set(wanted);
            self.in_flight += 1;
            return Ok(());
        }
        if status == STATUS_INVALID_HANDLE || status == STATUS_OBJECT_TYPE_MISMATCH {
            // The socket was closed while registered, with no operation in
            // flight to tell: the registration goes, as it does when the
            // system forgets a closed socket on its own.
            self.registrations.remove(&registration.socket);
            // SAFETY: out of the table, and the operation did not start.
            unsafe { self.free(ptr) };
            return Ok(());
        }
        self.enqueue(registration);
        Err(nt_error(status))
    }

    /// Asks the operation in flight of a registration to stop. Its
    /// completion still comes.
    fn cancel(&mut self, registration: &Registration) -> Result<()> {
        let helper = self.helpers[registration.helper].handle;
        let mut result = IoStatusBlock {
            status: 0,
            information: 0,
        };
        // Only the address of the block is used, to name the operation.
        // SAFETY: the address of a field of the allocation is taken; nothing
        // is read.
        let request = unsafe { &raw const (*registration.operation.get()).status };
        // SAFETY: `helper` is open; the system writes `result`.
        let status = unsafe { NtCancelIoFileEx(helper, request, &raw mut result) };
        // Not found: the operation is over and its completion on its way.
        if status >= 0 || status == STATUS_NOT_FOUND {
            registration.status.set(Status::Cancelled);
            Ok(())
        } else {
            Err(nt_error(status))
        }
    }

    /// Disposes of a registration taken out of the table: now, or when its
    /// operation is over.
    ///
    /// # Safety
    ///
    /// `ptr` must be a registration that was just removed from the table.
    unsafe fn retire(&mut self, ptr: *mut Registration) {
        // SAFETY: the registration is allocated.
        let registration = unsafe { &*ptr };
        registration.retired.set(true);
        match registration.status.get() {
            // SAFETY: out of the table, with no operation in flight.
            Status::Idle => unsafe { self.free(ptr) },
            Status::Pending => {
                // If it cannot be cancelled it will complete some day, or
                // when the poller is dropped.
                let _ = self.cancel(registration);
            }
            Status::Cancelled => {}
        }
    }

    /// Takes in the completion of the operation of `ptr`, and writes the
    /// event it makes, if any, at `events[*count]`.
    ///
    /// # Safety
    ///
    /// `ptr` must come from a completion packet of an operation.
    unsafe fn complete(
        &mut self,
        ptr: *mut Registration,
        events: &mut [RawEvent],
        count: &mut usize,
    ) {
        // SAFETY: an operation carries the address of its registration,
        // which is not freed while the operation is in flight.
        let registration = unsafe { &*ptr };
        self.in_flight -= 1;
        registration.status.set(Status::Idle);
        registration.watched.set(0);
        if registration.retired.get() {
            // SAFETY: out of the table, and its operation is over.
            unsafe { self.free(ptr) };
            return;
        }
        // SAFETY: the operation is over: the system is done writing.
        let (status, reported) = unsafe {
            let operation = &*registration.operation.get();
            let reported = if operation.info.count >= 1 {
                operation.info.handle.events
            } else {
                0
            };
            (operation.status.status as i32, reported)
        };
        let found = if status == STATUS_CANCELLED {
            0
        } else if status < 0 {
            // The operation failed in a way of its own: something is wrong
            // with the socket, which the caller's next call will tell.
            AFD_POLL_CONNECT_FAIL
        } else {
            reported
        };
        if found & AFD_POLL_LOCAL_CLOSE != 0 {
            // The socket was closed.
            self.registrations.remove(&registration.socket);
            // SAFETY: out of the table, and its operation is over.
            unsafe { self.free(ptr) };
            return;
        }
        if !registration.armed.get() {
            return;
        }
        let found = found & registration.wanted.get();
        if found == 0 {
            // Cancelled, or about what is no longer wanted: start again.
            self.enqueue(registration);
            return;
        }
        events[*count] = RawEvent {
            token: registration.token.get(),
            readiness: readiness(found),
            ..RawEvent::EMPTY
        };
        *count += 1;
        if registration.oneshot.get() {
            registration.armed.set(false);
        } else {
            // Level-triggered: polled again by the next wait.
            self.enqueue(registration);
        }
    }
}

/// A completion port.
struct Port(*mut c_void);

// SAFETY: a handle names a kernel object, which any thread may use.
unsafe impl Send for Port {}
// SAFETY: as above.
unsafe impl Sync for Port {}

pub(crate) struct Poller {
    port: Port,
    state: Lock<State>,
    /// A wake-up packet is in the port, or being reported.
    woken: AtomicBool,
    /// Never taken with the lock of `state` held, nor the other way round.
    timers: Lock<TimerState>,
}

/// The monotonic clock, in nanoseconds.
fn now() -> u64 {
    unbiased().saturating_mul(100)
}

impl Poller {
    pub(crate) fn new() -> Result<Self> {
        // SAFETY: with no file and no port, the function creates a port.
        let port = unsafe { CreateIoCompletionPort(INVALID_HANDLE_VALUE, null_mut(), 0, 0) };
        if port.is_null() {
            return Err(last_error());
        }
        Ok(Self {
            port: Port(port),
            state: Lock::new(State {
                registrations: BTreeMap::new(),
                queue: Vec::new(),
                helpers: Vec::new(),
                waiters: 0,
                in_flight: 0,
                waits: BTreeMap::new(),
                signals: BTreeMap::new(),
                sources: BTreeMap::new(),
                cookie: 0,
            }),
            woken: AtomicBool::new(false),
            timers: Lock::new(TimerState {
                timers: Timers::new(),
                timer: null_mut(),
                packet: null_mut(),
            }),
        })
    }

    /// Registers a waitable handle, or (`modify`) arms its registration
    /// again with another token.
    pub(crate) fn register_handle(
        &self,
        handle: RawHandle,
        token: usize,
        modify: bool,
    ) -> Result<()> {
        let mut state = self.state.lock();
        match (state.waits.get(&(handle as usize)), modify) {
            (Some(_), false) => return Err(ErrorKind::AlreadyExists.into()),
            (None, true) => return Err(ErrorKind::NotFound.into()),
            (None, false) => {}
            (Some(wait), true) => {
                // The old association goes first: one handle is waited for
                // once, and what the old one queued is not reported.
                let (packet, cookie) = (wait.packet, wait.cookie);
                state.sources.remove(&cookie);
                if !packet.is_null() {
                    // SAFETY: the packet of a registration is open, and
                    // this one is replaced below.
                    unsafe { discard_packet(packet) };
                }
                // Registered still, whatever happens next, but watching
                // nothing until a packet is made.
                state.waits.insert(
                    handle as usize,
                    Wait {
                        packet: null_mut(),
                        cookie: 0,
                    },
                );
            }
        }
        let packet = create_packet()?;
        let cookie = state.new_cookie();
        // Known before the association is made: its packet may come at
        // once, to a thread that is waiting.
        state.sources.insert(cookie, token);
        if let Err(error) = associate(packet, self.port.0, handle, KEY_SOURCE, cookie) {
            state.sources.remove(&cookie);
            // SAFETY: the packet was just created and is not used again.
            unsafe { CloseHandle(packet) };
            return Err(error);
        }
        state.waits.insert(handle as usize, Wait { packet, cookie });
        Ok(())
    }

    pub(crate) fn deregister_handle(&self, handle: RawHandle) -> Result<()> {
        let mut state = self.state.lock();
        let Some(wait) = state.waits.remove(&(handle as usize)) else {
            return Err(ErrorKind::NotFound.into());
        };
        state.sources.remove(&wait.cookie);
        if !wait.packet.is_null() {
            // SAFETY: the packet of a registration is open, and this one
            // is out of the table.
            unsafe { discard_packet(wait.packet) };
        }
        Ok(())
    }

    /// The process handle of the child, which is signaled once the process
    /// has exited, and from then on.
    pub(crate) fn register_child(
        &self,
        child: &crate::sys::process::Child,
        _collected: bool,
        token: usize,
    ) -> Result<()> {
        self.register_handle(child.handle().as_raw(), token, false)
    }

    pub(crate) fn deregister_child(&self, child: &crate::sys::process::Child) -> Result<()> {
        self.deregister_handle(child.handle().as_raw())
    }

    pub(crate) fn register_signals(
        &self,
        signals: &crate::sys::process::signal::Signals,
        token: usize,
    ) -> Result<()> {
        let set = signals.set();
        let mut state = self.state.lock();
        if state.signals.contains_key(&set) {
            return Err(ErrorKind::AlreadyExists.into());
        }
        let cookie = state.new_cookie();
        let mut hooks = HOOKS.lock();
        hooks.try_reserve(1).map_err(|_| ErrorKind::OutOfMemory)?;
        // Known before the handler is: it may post at once.
        state.sources.insert(cookie, token);
        state.signals.insert(set, cookie);
        hooks.push(Hook {
            set,
            port: self.port.0 as usize,
            cookie,
        });
        drop(hooks);
        if signals.is_pending() {
            // What came before the handler knew of the poller, which the
            // handler may be about to tell as well: one event too many is
            // a hint that was not needed.
            // SAFETY: the port is open.
            unsafe {
                PostQueuedCompletionStatus(self.port.0, 0, KEY_SOURCE, cookie as *const c_void)
            };
        }
        Ok(())
    }

    pub(crate) fn deregister_signals(
        &self,
        signals: &crate::sys::process::signal::Signals,
    ) -> Result<()> {
        let set = signals.set();
        let mut state = self.state.lock();
        let Some(cookie) = state.signals.remove(&set) else {
            return Err(ErrorKind::NotFound.into());
        };
        state.sources.remove(&cookie);
        // The handler posts with this lock held: once the hook is out, none
        // posts for it. (A subscription that was dropped took it out
        // already.)
        let port = self.port.0 as usize;
        HOOKS
            .lock()
            .retain(|hook| !(hook.port == port && hook.cookie == cookie));
        Ok(())
    }

    /// Arms the waitable timer for `deadline`, on the monotonic clock
    /// which reads `now`, or cancels it. A deadline that has passed fires
    /// it at once.
    fn arm(&self, state: &mut TimerState, deadline: Option<u64>, now: u64) -> Result<()> {
        if state.timer.is_null() {
            if deadline.is_none() {
                return Ok(());
            }
            // High-resolution if the system has such timers (Windows 10
            // 1803): the others count in ticks of the system's clock.
            for flags in [CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, 0] {
                // SAFETY: an unnamed timer with default security.
                state.timer =
                    unsafe { CreateWaitableTimerExW(null(), null(), flags, TIMER_ALL_ACCESS) };
                if !state.timer.is_null() {
                    break;
                }
            }
            if state.timer.is_null() {
                return Err(last_error());
            }
        }
        // The packet waits for what the timer was last armed for: it is
        // taken back, out of the port if it is there. When the system is
        // queuing it at this very moment it cannot be used again, and
        // another is made; the packet that comes finds nothing due.
        if !state.packet.is_null() && !cancel_packet(state.packet) {
            // SAFETY: the packet is open and not used again.
            unsafe { CloseHandle(state.packet) };
            state.packet = null_mut();
        }
        let Some(deadline) = deadline else {
            // SAFETY: the timer is open.
            unsafe { CancelWaitableTimer(state.timer) };
            return Ok(());
        };
        if state.packet.is_null() {
            state.packet = create_packet()?;
        }
        // Relative to now (a negative due time), in units of 100 ns
        // rounded up: an absolute one would be on the wall clock.
        let units = deadline.saturating_sub(now).div_ceil(100);
        let due = -(units.clamp(1, MAX_TIMER_UNITS) as i64);
        // SAFETY: the timer is open; the function reads the due time. No
        // period and no completion routine. Setting a timer makes it not
        // signaled, whatever it was.
        if unsafe { SetWaitableTimer(state.timer, &raw const due, 0, null(), null(), 0) } == 0 {
            return Err(last_error());
        }
        associate(state.packet, self.port.0, state.timer, KEY_TIMER, 0)
    }

    pub(crate) fn timer(&self, token: usize, op: Op) -> Result<()> {
        let mut state = self.timers.lock();
        let now = now();
        let mut timers = core::mem::replace(&mut state.timers, Timers::new());
        let result = timers.apply(token, op, now, |deadline| {
            self.arm(&mut state, deadline, now)
        });
        state.timers = timers;
        result
    }

    /// Writes the events of the timers that are due at the start of
    /// `events`, returns their count, and arms the waitable timer for what
    /// comes next: its packet was collected, and comes once for each
    /// arming. What is due and does not fit is the next deadline, which
    /// has passed: the timer fires at once.
    fn expire(&self, events: &mut [RawEvent]) -> Result<usize> {
        let mut state = self.timers.lock();
        let now = now();
        let count = state
            .timers
            .expire(now, events.len(), |index, token, expirations| {
                events[index] = RawEvent {
                    token,
                    expirations,
                    ..RawEvent::EMPTY
                };
            });
        let next = state.timers.next();
        self.arm(&mut state, next, now).map(|()| count)
    }

    pub(crate) fn register(
        &self,
        socket: RawSocket,
        token: usize,
        interest: Interest,
        mode: ModeKind,
    ) -> Result<()> {
        let oneshot = match mode {
            ModeKind::Level => false,
            ModeKind::OneShot => true,
            // Not offered on Windows.
            ModeKind::Edge => return Err(ErrorKind::Unsupported.into()),
        };
        let base = base_socket(socket)? as *mut c_void;
        let mut state = self.state.lock();
        if state.registrations.contains_key(&socket) {
            // Registered already, or (the same number) a socket that was
            // closed while registered and that no operation was watching.
            return Err(ErrorKind::AlreadyExists.into());
        }
        let helper = state.helper(self.port.0)?;
        state
            .queue
            .try_reserve(1)
            .map_err(|_| ErrorKind::OutOfMemory)?;
        let ptr = Box::into_raw(Box::new(Registration {
            operation: UnsafeCell::new(Operation {
                status: IoStatusBlock {
                    status: 0,
                    information: 0,
                },
                info: AfdPollInfo {
                    timeout: 0,
                    count: 0,
                    exclusive: 0,
                    handle: AfdPollHandleInfo {
                        handle: null_mut(),
                        events: 0,
                        status: 0,
                    },
                },
            }),
            socket,
            base,
            helper,
            token: Cell::new(token),
            wanted: Cell::new(afd_events(interest)),
            oneshot: Cell::new(oneshot),
            armed: Cell::new(true),
            status: Cell::new(Status::Idle),
            watched: Cell::new(0),
            retired: Cell::new(false),
            queued: Cell::new(false),
        }));
        state.helpers[helper].users += 1;
        state.registrations.insert(socket, ptr);
        // SAFETY: `ptr` was just allocated.
        state.enqueue(unsafe { &*ptr });
        if state.waiters > 0 {
            // A thread is waiting: its wait must learn of the socket.
            state.flush()?;
        }
        Ok(())
    }

    pub(crate) fn modify(
        &self,
        socket: RawSocket,
        token: usize,
        interest: Interest,
        mode: ModeKind,
    ) -> Result<()> {
        let oneshot = match mode {
            ModeKind::Level => false,
            ModeKind::OneShot => true,
            ModeKind::Edge => return Err(ErrorKind::Unsupported.into()),
        };
        let mut state = self.state.lock();
        let Some(&ptr) = state.registrations.get(&socket) else {
            return Err(ErrorKind::NotFound.into());
        };
        // SAFETY: a registration in the table is allocated.
        let registration = unsafe { &*ptr };
        registration.token.set(token);
        registration.wanted.set(afd_events(interest));
        registration.oneshot.set(oneshot);
        registration.armed.set(true);
        state.enqueue(registration);
        if state.waiters > 0 {
            state.flush()?;
        }
        Ok(())
    }

    pub(crate) fn deregister(&self, socket: RawSocket) -> Result<()> {
        let mut state = self.state.lock();
        let Some(ptr) = state.registrations.remove(&socket) else {
            return Err(ErrorKind::NotFound.into());
        };
        // SAFETY: `ptr` was just removed from the table.
        unsafe { state.retire(ptr) };
        Ok(())
    }

    pub(crate) fn wait(&self, events: &mut [RawEvent], timeout: Option<Duration>) -> Result<usize> {
        // On the unbiased interrupt time, the clock `Clock::Monotonic`
        // reads: the port counts in milliseconds and in timer ticks.
        let deadline = timeout.map(|timeout| unbiased().saturating_add(to_units(timeout)));
        let want = events.len().min(BATCH) as u32;
        loop {
            {
                let mut state = self.state.lock();
                state.flush()?;
                state.waiters += 1;
            }
            let milliseconds = match deadline {
                None => INFINITE,
                Some(deadline) => {
                    let left = deadline.saturating_sub(unbiased()).div_ceil(UNITS_PER_MS);
                    // In pieces if it is more than the port counts (49
                    // days; `INFINITE`, the largest value, means no
                    // timeout): the loop goes on until the deadline.
                    u32::try_from(left).unwrap_or(INFINITE).min(INFINITE - 1)
                }
            };
            let mut entries = [OverlappedEntry::EMPTY; BATCH];
            let mut removed = 0;
            // SAFETY: the function writes at most `want` entries, and how
            // many it wrote.
            let collected = unsafe {
                GetQueuedCompletionStatusEx(
                    self.port.0,
                    entries.as_mut_ptr(),
                    want,
                    &raw mut removed,
                    milliseconds,
                    0,
                )
            };
            let error = (collected == 0).then(last_error);

            let mut state = self.state.lock();
            state.waiters -= 1;
            if let Some(error) = error {
                if error.raw_os_error() != WAIT_TIMEOUT {
                    return Err(error);
                }
                removed = 0;
            }
            let mut count = 0;
            let mut timer_fired = false;
            // Each packet makes one event at most, but for the timer's,
            // which makes none here and leaves room for one.
            for entry in &entries[..(removed as usize).min(BATCH)] {
                if entry.key == KEY_TIMER {
                    timer_fired = true;
                } else if entry.key == KEY_SOURCE {
                    // A handle that is signaled, or a console control
                    // event: the cookie is a number, and one that is no
                    // longer known is of a registration that is gone.
                    if let Some(&token) = state.sources.get(&(entry.overlapped as usize)) {
                        events[count] = RawEvent {
                            token,
                            readiness: Readiness::READABLE,
                            ..RawEvent::EMPTY
                        };
                        count += 1;
                    }
                } else if entry.overlapped.is_null() {
                    // The packet of `wake`, which may now post another.
                    self.woken.store(false, Ordering::Release);
                    events[count] = RawEvent {
                        wake: true,
                        ..RawEvent::EMPTY
                    };
                    count += 1;
                } else if entry.key == KEY_SOCKET {
                    // SAFETY: the only other packets with this key are the
                    // completions of the operations on the helper handles,
                    // whose context is their registration.
                    unsafe { state.complete(entry.overlapped.cast(), events, &mut count) };
                }
            }
            if state.waiters > 0 {
                // What this thread would start by its next wait, the
                // threads that are waiting now need started. A failure is
                // reported by the next wait, which tries again.
                let _ = state.flush();
            }
            drop(state);
            if timer_fired {
                match self.expire(&mut events[count..]) {
                    Ok(expired) => count += expired,
                    // What was collected is not lost to an error.
                    Err(_) if count > 0 => {}
                    Err(error) => return Err(error),
                }
            }
            if count > 0 {
                return Ok(count);
            }
            // Nothing to report: either the time is up, or the completions
            // were not events (operations cancelled, sockets closed, events
            // no longer wanted) and the wait goes on.
            if removed == 0
                && let Some(deadline) = deadline
                && unbiased() >= deadline
            {
                return Ok(0);
            }
        }
    }

    pub(crate) fn wake(&self) -> Result<()> {
        if self.woken.swap(true, Ordering::AcqRel) {
            // A packet is on its way to a wait already.
            return Ok(());
        }
        // SAFETY: the port is open. A packet with no overlapped structure
        // is what tells it from a completion.
        if unsafe { PostQueuedCompletionStatus(self.port.0, 0, 0, null()) } == 0 {
            let error = last_error();
            self.woken.store(false, Ordering::Release);
            return Err(error);
        }
        Ok(())
    }
}

impl Drop for Poller {
    fn drop(&mut self) {
        // No handler of console control events posts to the port from
        // here on: it posts with this lock held.
        let port = self.port.0 as usize;
        HOOKS.lock().retain(|hook| hook.port != port);
        {
            let state = self.timers.lock();
            // SAFETY: the handles are open, owned and not used again. A
            // packet that is queued all the same is dropped with the port.
            unsafe {
                if !state.packet.is_null() {
                    discard_packet(state.packet);
                }
                if !state.timer.is_null() {
                    CloseHandle(state.timer);
                }
            }
        }
        let mut state = self.state.lock();
        for wait in core::mem::take(&mut state.waits).into_values() {
            if !wait.packet.is_null() {
                // SAFETY: the packet of a registration is open, and this
                // one is out of the table.
                unsafe { discard_packet(wait.packet) };
            }
        }
        // Every registration goes: at once if the system holds nothing of
        // it, when its cancelled operation comes back otherwise.
        let registrations = core::mem::take(&mut state.registrations);
        for &ptr in registrations.values() {
            // SAFETY: `ptr` was just removed from the table.
            unsafe { state.retire(ptr) };
        }
        let mut patience = DRAIN_PATIENCE;
        while state.in_flight > 0 && patience > 0 {
            let mut entries = [OverlappedEntry::EMPTY; BATCH];
            let mut removed = 0;
            // SAFETY: the function writes at most `BATCH` entries, and how
            // many it wrote.
            let collected = unsafe {
                GetQueuedCompletionStatusEx(
                    self.port.0,
                    entries.as_mut_ptr(),
                    BATCH as u32,
                    &raw mut removed,
                    DRAIN_MILLISECONDS,
                    0,
                )
            };
            if collected == 0 {
                patience -= 1;
                continue;
            }
            patience = DRAIN_PATIENCE;
            for entry in &entries[..(removed as usize).min(BATCH)] {
                // The other packets carry numbers, not registrations.
                if entry.key == KEY_SOCKET && !entry.overlapped.is_null() {
                    let ptr = entry.overlapped.cast::<Registration>();
                    state.in_flight -= 1;
                    // SAFETY: the completion of an operation, whose
                    // registration is retired: the system is done with it.
                    unsafe {
                        (*ptr).status.set(Status::Idle);
                        state.free(ptr);
                    }
                }
            }
        }
        // The registrations whose operation did not come back are leaked:
        // the system may still write to them.
        for helper in &state.helpers {
            // SAFETY: the handle is open, owned and not used again.
            unsafe { CloseHandle(helper.handle) };
        }
        // SAFETY: as above.
        unsafe { CloseHandle(self.port.0) };
    }
}