hisi-rf-core 0.1.0-alpha.24

Chip-neutral async radio controller contracts for HiSilicon embedded Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
use portable_atomic::Ordering;

use crate::state::{SharedState, saturating_increment};
use crate::{DiagnosticStage, DiagnosticTrace, DiagnosticTraceKind, Error};

pub mod security;
pub use security::{ManagementFrameProtection, PersonalSecurity, SaePwe};

pub(crate) const MAX_SCAN_RESULTS: usize = 32;
const SSID_CAPACITY: usize = 32;
const PASSPHRASE_CAPACITY: usize = 63;

/// Radio-wide configuration.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub struct RadioConfig {
    /// Wi-Fi control-plane defaults.
    pub wifi: WifiConfig,
}

/// Wi-Fi control-plane defaults.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct WifiConfig {
    /// Backend lifecycle timeout for radio initialization.
    pub initialize_timeout: BackendTimeout,
    /// Backend lifecycle timeout for disconnect cleanup.
    pub disconnect_timeout: BackendTimeout,
}

impl Default for WifiConfig {
    fn default() -> Self {
        Self {
            initialize_timeout: BackendTimeout::from_millis_const(30_000),
            disconnect_timeout: BackendTimeout::from_millis_const(10_000),
        }
    }
}

/// Non-zero end-to-end timeout for one protocol operation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct OperationTimeout(u32);

impl OperationTimeout {
    /// Validate a non-zero timeout in milliseconds.
    pub const fn try_from_millis(milliseconds: u32) -> Option<Self> {
        if milliseconds == 0 {
            None
        } else {
            Some(Self(milliseconds))
        }
    }

    /// Return the timeout in milliseconds.
    pub const fn as_millis(self) -> u32 {
        self.0
    }
}

/// Non-zero timeout for a bounded backend or vendor lifecycle call.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct BackendTimeout(u32);

impl BackendTimeout {
    /// Validate a non-zero timeout in milliseconds.
    pub const fn try_from_millis(milliseconds: u32) -> Option<Self> {
        if milliseconds == 0 {
            None
        } else {
            Some(Self(milliseconds))
        }
    }

    /// Return the timeout in milliseconds.
    pub const fn as_millis(self) -> u32 {
        self.0
    }

    const fn from_millis_const(milliseconds: u32) -> Self {
        assert!(milliseconds != 0);
        Self(milliseconds)
    }
}

/// Immutable link-layer identity published by one initialized Wi-Fi backend.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct WifiL2Capabilities {
    station_mac_address: [u8; 6],
}

impl WifiL2Capabilities {
    /// Validate a non-zero unicast station MAC address.
    pub const fn try_new(station_mac_address: [u8; 6]) -> Option<Self> {
        let any_nonzero = station_mac_address[0]
            | station_mac_address[1]
            | station_mac_address[2]
            | station_mac_address[3]
            | station_mac_address[4]
            | station_mac_address[5];
        if any_nonzero == 0 || station_mac_address[0] & 1 != 0 {
            None
        } else {
            Some(Self {
                station_mac_address,
            })
        }
    }

    /// Return the station MAC address owned by this radio instance.
    pub const fn station_mac_address(self) -> [u8; 6] {
        self.station_mac_address
    }
}

/// Validated IEEE 802.11 SSID bytes.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Ssid {
    bytes: [u8; SSID_CAPACITY],
    len: u8,
}

impl Ssid {
    /// Validate and copy a non-empty SSID of at most 32 bytes.
    pub fn try_from_bytes(value: &[u8]) -> Option<Self> {
        if value.is_empty() || value.len() > SSID_CAPACITY {
            return None;
        }
        let mut bytes = [0; SSID_CAPACITY];
        bytes[..value.len()].copy_from_slice(value);
        Some(Self {
            bytes,
            len: value.len() as u8,
        })
    }

    /// Return the exact SSID bytes.
    pub fn as_bytes(&self) -> &[u8] {
        &self.bytes[..self.len as usize]
    }
}

/// Owned WPA2/WPA3-Personal passphrase that is erased on drop.
#[derive(Debug, Eq, PartialEq)]
pub struct Passphrase {
    bytes: [u8; PASSPHRASE_CAPACITY],
    len: u8,
}

impl Passphrase {
    /// Validate and copy an 8-63 byte printable ASCII passphrase.
    pub fn try_from_ascii(value: &[u8]) -> Option<Self> {
        if !(8..=PASSPHRASE_CAPACITY).contains(&value.len())
            || value.iter().any(|byte| *byte < 32 || *byte == 127)
        {
            return None;
        }
        let mut bytes = [0; PASSPHRASE_CAPACITY];
        bytes[..value.len()].copy_from_slice(value);
        Some(Self {
            bytes,
            len: value.len() as u8,
        })
    }

    /// Borrow the passphrase bytes for a backend call.
    pub fn expose_secret(&self) -> &[u8] {
        &self.bytes[..self.len as usize]
    }
}

impl Drop for Passphrase {
    fn drop(&mut self) {
        for byte in &mut self.bytes {
            // Volatile stores keep secret erasure observable to the compiler.
            // SAFETY: `byte` uniquely borrows one live element of this owned
            // array and is valid for a one-byte volatile write.
            unsafe { core::ptr::write_volatile(byte, 0) };
        }
        self.len = 0;
    }
}

/// Link-layer security discovered during scan.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Security {
    /// Open network.
    Open,
    /// WPA2-Personal with CCMP.
    Wpa2Personal,
    /// WPA3-Personal with SAE and mandatory PMF.
    Wpa3Personal,
    /// WPA2/WPA3-Personal transition BSS advertising both PSK and SAE.
    ///
    /// Applications must explicitly choose WPA2 or WPA3 when constructing the
    /// station configuration; discovery never silently downgrades the link.
    Wpa2Wpa3PersonalTransition,
    /// A protected mode not yet represented by this public API.
    OtherProtected,
}

/// One chip-neutral bounded scan result.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ScanResult {
    /// Advertised SSID.
    pub ssid: Ssid,
    /// Basic service set identifier.
    pub bssid: [u8; 6],
    /// Center frequency in MHz.
    pub frequency_mhz: u16,
    /// Signal strength in dBm.
    pub rssi_dbm: i16,
    /// Link-layer security class.
    pub security: Security,
    /// Primary channel when known, otherwise zero.
    pub channel: u8,
}

impl ScanResult {
    pub(crate) const EMPTY: Self = Self {
        ssid: Ssid {
            bytes: [0; SSID_CAPACITY],
            len: 0,
        },
        bssid: [0; 6],
        frequency_mhz: 0,
        rssi_dbm: 0,
        security: Security::Open,
        channel: 0,
    };

    /// Empty value for caller-provided fixed scan buffers.
    pub const fn empty() -> Self {
        Self::EMPTY
    }
}

/// Bounded station scan request.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ScanConfig {
    operation_timeout: OperationTimeout,
}

impl ScanConfig {
    /// Construct a bounded scan request.
    pub const fn new(operation_timeout: OperationTimeout) -> Self {
        Self { operation_timeout }
    }

    /// End-to-end scan timeout enforced by the protocol backend.
    pub const fn operation_timeout(self) -> OperationTimeout {
        self.operation_timeout
    }
}

/// Result count for a caller-provided scan buffer.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ScanOutcome {
    /// Entries copied into the caller's buffer.
    pub count: usize,
    /// At least one result did not fit in the backend or caller buffer.
    pub truncated: bool,
}

/// Validated station connection request.
#[derive(Debug, Eq, PartialEq)]
pub struct StationConfig {
    /// SSID selected by the application.
    pub ssid: Ssid,
    /// BSSID selected by the immediately preceding scan.
    pub bssid: [u8; 6],
    /// Primary channel selected by the immediately preceding scan.
    pub channel: u8,
    /// WPA2/WPA3-Personal passphrase.
    pub passphrase: Passphrase,
    security: PersonalSecurity,
    operation_timeout: OperationTimeout,
}

impl StationConfig {
    /// Select a WPA2-Personal scan result and take ownership of its passphrase.
    pub fn wpa2_personal(
        result: &ScanResult,
        passphrase: Passphrase,
        operation_timeout: OperationTimeout,
    ) -> Option<Self> {
        if !matches!(
            result.security,
            Security::Wpa2Personal | Security::Wpa2Wpa3PersonalTransition
        ) {
            return None;
        }
        Some(Self {
            ssid: result.ssid,
            bssid: result.bssid,
            channel: result.channel,
            passphrase,
            security: PersonalSecurity::Wpa2,
            operation_timeout,
        })
    }

    /// Select a WPA3-Personal scan result and take ownership of its passphrase.
    ///
    /// PMF is mandatory by construction; callers only choose the SAE
    /// password-element policy supported by their controlled deployment.
    pub fn wpa3_personal(
        result: &ScanResult,
        passphrase: Passphrase,
        sae_pwe: SaePwe,
        operation_timeout: OperationTimeout,
    ) -> Option<Self> {
        if !matches!(
            result.security,
            Security::Wpa3Personal | Security::Wpa2Wpa3PersonalTransition
        ) {
            return None;
        }
        Some(Self {
            ssid: result.ssid,
            bssid: result.bssid,
            channel: result.channel,
            passphrase,
            security: PersonalSecurity::Wpa3 { sae_pwe },
            operation_timeout,
        })
    }

    /// Typed Personal-mode security consumed by the chip backend.
    pub const fn security(&self) -> PersonalSecurity {
        self.security
    }

    /// End-to-end association and authorization timeout.
    pub const fn operation_timeout(&self) -> OperationTimeout {
        self.operation_timeout
    }
}

/// Successful station association.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ConnectionInfo {
    /// Associated BSSID.
    pub bssid: [u8; 6],
    /// Associated center frequency in MHz.
    pub frequency_mhz: u16,
}

/// Stable class for backend-specific failures.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BackendErrorClass {
    /// Radio initialization failed.
    Initialize,
    /// The requested operation is already active.
    Busy,
    /// The end-to-end protocol operation timeout elapsed.
    OperationTimeout,
    /// A bounded backend or vendor lifecycle call timed out.
    BackendTimeout,
    /// The operation was explicitly cancelled before completion.
    Cancelled,
    /// The selected profile could not acquire a required bounded resource.
    ResourceUnavailable,
    /// The requested security mode is unsupported.
    UnsupportedSecurity,
    /// Association or authorization failed.
    Connect,
    /// A chip-specific failure outside the stable classes.
    Other,
}

/// Backend error with a stable class and lossless chip-specific context.
///
/// Chip backends construct this value explicitly instead of exposing their
/// private error enums through the portable API. The fixed-size diagnostic
/// context remains allocation-free and contains no arbitrary backend text.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct BackendError {
    /// Stable failure class.
    class: BackendErrorClass,
    /// Chip/backend-specific diagnostic code.
    code: u32,
    stage: DiagnosticStage,
    profile_revision: Option<&'static str>,
    trace: DiagnosticTrace,
}

impl BackendError {
    /// Create an error with a stable class and lossless backend code.
    pub const fn new(class: BackendErrorClass, code: u32) -> Self {
        let stage = match class {
            BackendErrorClass::Initialize => DiagnosticStage::Initialize,
            BackendErrorClass::UnsupportedSecurity | BackendErrorClass::Connect => {
                DiagnosticStage::Connect
            }
            BackendErrorClass::Busy
            | BackendErrorClass::OperationTimeout
            | BackendErrorClass::Cancelled => DiagnosticStage::Operation,
            BackendErrorClass::BackendTimeout => DiagnosticStage::Backend,
            BackendErrorClass::ResourceUnavailable => DiagnosticStage::Runtime,
            BackendErrorClass::Other => DiagnosticStage::Backend,
        };
        Self {
            class,
            code,
            stage,
            profile_revision: None,
            trace: DiagnosticTrace::new(),
        }
    }

    /// Stable backend failure class.
    pub const fn class(self) -> BackendErrorClass {
        self.class
    }

    /// Lossless chip/backend-specific code.
    pub const fn code(self) -> u32 {
        self.code
    }

    /// Attach the protocol stage known by the backend.
    pub const fn with_stage(mut self, stage: DiagnosticStage) -> Self {
        self.stage = stage;
        self
    }

    /// Attach the immutable backend/profile revision used by this firmware.
    pub const fn with_profile_revision(mut self, revision: &'static str) -> Self {
        self.profile_revision = Some(revision);
        self
    }

    /// Append one bounded numeric trace entry.
    pub fn with_trace(mut self, kind: DiagnosticTraceKind, value: u32) -> Self {
        self.trace.push(kind, value);
        self
    }

    pub(crate) const fn stage(self) -> DiagnosticStage {
        self.stage
    }

    pub(crate) const fn profile_revision(self) -> Option<&'static str> {
        self.profile_revision
    }

    pub(crate) const fn trace(self) -> DiagnosticTrace {
        self.trace
    }
}

/// Successful and failed state transitions emitted by the runner.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WifiEvent {
    /// Backend initialization completed.
    Initialized,
    /// Scan completed and retained this many results.
    ScanCompleted { count: usize, truncated: bool },
    /// Station association and authorization completed.
    Connected(ConnectionInfo),
    /// The station disconnected.
    Disconnected { reason: u16 },
    /// An operation failed in the backend.
    Failed(BackendError),
}

/// Event queue overflow diagnostics.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct EventDiagnostics {
    /// Compile-time queue depth.
    pub capacity: usize,
    /// Events accepted into the bounded queue.
    pub accepted: u32,
    /// Events consumed by the controller.
    pub consumed: u32,
    /// Events currently waiting for the controller.
    pub pending: usize,
    /// Largest observed queue occupancy since initialization.
    pub high_water: usize,
    /// Oldest events discarded because the queue was full.
    pub dropped: u32,
}

/// Observational counters for the blocking [`RadioRunner`] path.
///
/// Counters saturate at `u32::MAX`. They describe migration workload and must
/// not be used as synchronization or correctness state.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct BlockingRunnerDiagnostics {
    /// Commands currently waiting in the fixed-capacity control channel.
    pub command_queue_pending: usize,
    /// Largest observed control-channel occupancy since initialization.
    pub command_queue_high_water: usize,
    /// Calls to [`RadioRunner::run_once`].
    pub run_once_calls: u32,
    /// Commands processed by either runner entry point.
    pub commands_processed: u32,
    /// Calls to [`WifiBackend::poll`].
    pub backend_poll_calls: u32,
    /// Poll calls that reported useful background work.
    pub backend_poll_work_batches: u32,
    /// Poll calls that returned an error, including repeated errors.
    pub backend_poll_errors: u32,
    /// `run_once` calls that asked the platform to schedule another batch.
    pub immediate_repoll_hints: u32,
}

/// Chip backend driven exclusively by [`RadioRunner`].
pub trait WifiBackend {
    /// Initialize the vendor/ROM radio runtime.
    fn initialize(&mut self, config: &WifiConfig) -> Result<(), BackendError>;

    /// Scan into the fixed runner-owned buffer.
    fn scan(
        &mut self,
        config: ScanConfig,
        output: &mut [ScanResult],
    ) -> Result<ScanOutcome, BackendError>;

    /// Associate and authorize one station connection.
    fn connect(&mut self, config: &StationConfig) -> Result<ConnectionInfo, BackendError>;

    /// Disconnect the station interface.
    fn disconnect(&mut self, config: &WifiConfig) -> Result<(), BackendError>;

    /// Snapshot immutable L2 identity after successful initialization.
    ///
    /// The runner publishes the first returned value into this radio
    /// instance's state. It never exposes an unowned process-global accessor.
    fn l2_capabilities(&self) -> Option<WifiL2Capabilities> {
        None
    }

    /// Advance bounded background work owned by the radio runner.
    ///
    /// Push-only backends may keep the default implementation. Host-side
    /// protocol engines use this seam for event-loop deadlines and queued RX;
    /// it must not invoke application callbacks.
    fn poll(&mut self) -> Result<bool, BackendError> {
        Ok(false)
    }
}

/// Caller-provided chip resources.
pub struct RadioResources<B, D> {
    /// Control-plane backend moved into the runner.
    pub backend: B,
    /// L2 device moved into the Wi-Fi data plane.
    pub device: D,
}

/// Static storage for one radio controller and its bounded event queue.
pub struct RadioState<const EVENTS: usize> {
    pub(crate) shared: SharedState<EVENTS>,
}

impl<const EVENTS: usize> RadioState<EVENTS> {
    /// Construct unclaimed radio state suitable for static allocation.
    pub const fn new() -> Self {
        Self {
            shared: SharedState::new(),
        }
    }
}

impl<const EVENTS: usize> Default for RadioState<EVENTS> {
    fn default() -> Self {
        Self::new()
    }
}

/// Exclusive unsplit radio ownership.
pub struct RadioController<B, D, const EVENTS: usize> {
    config: RadioConfig,
    resources: RadioResources<B, D>,
    state: &'static RadioState<EVENTS>,
}

/// Claim one radio instance without invoking its backend.
pub fn init<B, D, const EVENTS: usize>(
    config: RadioConfig,
    resources: RadioResources<B, D>,
    state: &'static RadioState<EVENTS>,
) -> Result<RadioController<B, D, EVENTS>, Error> {
    if !state.shared.claim() {
        return Err(Error::AlreadyInitialized);
    }
    Ok(RadioController {
        config,
        resources,
        state,
    })
}

impl<B, D, const EVENTS: usize> RadioController<B, D, EVENTS> {
    /// Split exclusive ownership into Wi-Fi control/data planes and the runner.
    pub fn split(self) -> RadioParts<B, D, EVENTS> {
        let (wifi, backend, config, state) = self.split_components();
        RadioParts {
            wifi,
            runner: RadioRunner {
                backend,
                config,
                state,
                last_poll_error: None,
            },
        }
    }

    pub(crate) fn split_components(
        self,
    ) -> (
        WifiParts<D, EVENTS>,
        B,
        WifiConfig,
        &'static RadioState<EVENTS>,
    ) {
        (
            WifiParts {
                controller: WifiController {
                    state: self.state,
                    next_sequence: 0,
                },
                device: WifiDevice {
                    inner: self.resources.device,
                    l2_capabilities: &self.state.shared.l2_capabilities,
                },
            },
            self.resources.backend,
            self.config.wifi,
            self.state,
        )
    }
}

/// Enabled protocol handles plus the mandatory runner.
pub struct RadioParts<B, D, const EVENTS: usize> {
    /// Wi-Fi control and L2 data planes.
    pub wifi: WifiParts<D, EVENTS>,
    /// Long-lived backend runner.
    pub runner: RadioRunner<B, EVENTS>,
}

/// Separate Wi-Fi control and L2 data-plane ownership.
pub struct WifiParts<D, const EVENTS: usize> {
    /// Async control plane.
    pub controller: WifiController<EVENTS>,
    /// L2 data plane.
    pub device: WifiDevice<D>,
}

/// Async Wi-Fi control plane. This handle is deliberately not cloneable.
pub struct WifiController<const EVENTS: usize> {
    state: &'static RadioState<EVENTS>,
    next_sequence: u32,
}

struct OperationCancellation<const EVENTS: usize> {
    state: &'static RadioState<EVENTS>,
    sequence: u32,
    armed: bool,
}

impl<const EVENTS: usize> OperationCancellation<EVENTS> {
    const fn new(state: &'static RadioState<EVENTS>, sequence: u32) -> Self {
        Self {
            state,
            sequence,
            armed: true,
        }
    }

    fn complete(&mut self) {
        self.armed = false;
    }
}

impl<const EVENTS: usize> Drop for OperationCancellation<EVENTS> {
    fn drop(&mut self) {
        if self.armed {
            // The unique controller can have at most one command in the facade
            // channel, one pending in the incremental driver, and one active
            // operation. The three-entry cancellation channel therefore
            // covers every accepted-but-unobserved control future.
            let _ = self.state.shared.cancellations.try_send(self.sequence);
        }
    }
}

impl<const EVENTS: usize> WifiController<EVENTS> {
    /// Ask the runner to initialize the backend.
    ///
    /// Dropping this future requests cancellation. The unique runner performs
    /// backend abort and cleanup outside the drop path.
    pub async fn initialize(&mut self) -> Result<(), Error> {
        let sequence = self.allocate_sequence();
        self.send_command(Command {
            sequence,
            kind: CommandKind::Initialize,
        })
        .await;
        let mut cancellation = OperationCancellation::new(self.state, sequence);
        loop {
            let completion = self.state.shared.completion.wait().await;
            if completion.sequence != sequence {
                continue;
            }
            let result = match completion.kind {
                CompletionKind::Initialize(result) => result.map_err(Error::Backend),
                #[cfg(feature = "incremental-backend-experiment")]
                CompletionKind::Protocol => Err(Error::Protocol),
                _ => Err(Error::Protocol),
            };
            cancellation.complete();
            return result;
        }
    }

    /// Scan and copy results into a caller-provided fixed buffer.
    pub async fn scan(
        &mut self,
        config: ScanConfig,
        output: &mut [ScanResult],
    ) -> Result<ScanOutcome, Error> {
        let sequence = self.allocate_sequence();
        self.send_command(Command {
            sequence,
            kind: CommandKind::Scan(config),
        })
        .await;
        let mut cancellation = OperationCancellation::new(self.state, sequence);
        loop {
            let completion = self.state.shared.completion.wait().await;
            if completion.sequence != sequence {
                continue;
            }
            let result = match completion.kind {
                CompletionKind::Scan(result) => match result {
                    Ok(backend) => {
                        let count = backend.count.min(output.len());
                        output[..count].copy_from_slice(&self.state.shared.scan_results()[..count]);
                        Ok(ScanOutcome {
                            count,
                            truncated: backend.truncated || backend.count > output.len(),
                        })
                    }
                    Err(error) => Err(Error::Backend(error)),
                },
                #[cfg(feature = "incremental-backend-experiment")]
                CompletionKind::Protocol => Err(Error::Protocol),
                _ => Err(Error::Protocol),
            };
            cancellation.complete();
            return result;
        }
    }

    /// Associate and authorize a station connection.
    pub async fn connect(&mut self, config: StationConfig) -> Result<ConnectionInfo, Error> {
        let sequence = self.allocate_sequence();
        self.send_command(Command {
            sequence,
            kind: CommandKind::Connect(config),
        })
        .await;
        let mut cancellation = OperationCancellation::new(self.state, sequence);
        loop {
            let completion = self.state.shared.completion.wait().await;
            if completion.sequence != sequence {
                continue;
            }
            let result = match completion.kind {
                CompletionKind::Connect(result) => result.map_err(Error::Backend),
                #[cfg(feature = "incremental-backend-experiment")]
                CompletionKind::Protocol => Err(Error::Protocol),
                _ => Err(Error::Protocol),
            };
            cancellation.complete();
            return result;
        }
    }

    /// Disconnect the current station link.
    pub async fn disconnect(&mut self) -> Result<(), Error> {
        let sequence = self.allocate_sequence();
        self.send_command(Command {
            sequence,
            kind: CommandKind::Disconnect,
        })
        .await;
        let mut cancellation = OperationCancellation::new(self.state, sequence);
        loop {
            let completion = self.state.shared.completion.wait().await;
            if completion.sequence != sequence {
                continue;
            }
            let result = match completion.kind {
                CompletionKind::Disconnect(result) => result.map_err(Error::Backend),
                #[cfg(feature = "incremental-backend-experiment")]
                CompletionKind::Protocol => Err(Error::Protocol),
                _ => Err(Error::Protocol),
            };
            cancellation.complete();
            return result;
        }
    }

    /// Wait for the next bounded event produced by the runner.
    pub async fn next_event(&mut self) -> WifiEvent {
        let event = self.state.shared.events.receive().await;
        saturating_increment(&self.state.shared.consumed_events);
        event
    }

    /// Snapshot queue occupancy and overflow.
    pub fn event_diagnostics(&self) -> EventDiagnostics {
        EventDiagnostics {
            capacity: EVENTS,
            accepted: self.state.shared.accepted_events.load(Ordering::Relaxed),
            consumed: self.state.shared.consumed_events.load(Ordering::Relaxed),
            pending: self.state.shared.events.len(),
            high_water: usize::try_from(self.state.shared.event_high_water.load(Ordering::Relaxed))
                .unwrap_or(usize::MAX),
            dropped: self.state.shared.dropped_events.load(Ordering::Relaxed),
        }
    }

    /// Snapshot blocking-runner migration counters.
    pub fn blocking_runner_diagnostics(&self) -> BlockingRunnerDiagnostics {
        BlockingRunnerDiagnostics {
            command_queue_pending: self.state.shared.commands.len(),
            command_queue_high_water: usize::try_from(
                self.state.shared.command_high_water.load(Ordering::Relaxed),
            )
            .unwrap_or(usize::MAX),
            run_once_calls: self.state.shared.run_once_calls.load(Ordering::Relaxed),
            commands_processed: self.state.shared.commands_processed.load(Ordering::Relaxed),
            backend_poll_calls: self.state.shared.backend_poll_calls.load(Ordering::Relaxed),
            backend_poll_work_batches: self
                .state
                .shared
                .backend_poll_work_batches
                .load(Ordering::Relaxed),
            backend_poll_errors: self
                .state
                .shared
                .backend_poll_errors
                .load(Ordering::Relaxed),
            immediate_repoll_hints: self
                .state
                .shared
                .immediate_repoll_hints
                .load(Ordering::Relaxed),
        }
    }

    /// Snapshot the opt-in incremental runner counters for this radio instance.
    #[cfg(feature = "incremental-backend-experiment")]
    pub fn incremental_runner_diagnostics(&self) -> crate::IncrementalRunnerDiagnostics {
        self.state.shared.incremental_diagnostics.snapshot()
    }

    fn allocate_sequence(&mut self) -> u32 {
        self.next_sequence = self.next_sequence.wrapping_add(1);
        if self.next_sequence == 0 {
            self.next_sequence = 1;
        }
        self.next_sequence
    }

    async fn send_command(&self, command: Command) {
        self.state.shared.commands.send(command).await;
        self.state.shared.record_command_accepted();
    }
}

/// Long-lived owner of a chip backend.
pub struct RadioRunner<B, const EVENTS: usize> {
    backend: B,
    config: WifiConfig,
    state: &'static RadioState<EVENTS>,
    last_poll_error: Option<BackendError>,
}

impl<B: WifiBackend, const EVENTS: usize> RadioRunner<B, EVENTS> {
    /// Process at most one command and one bounded background-work batch.
    ///
    /// A `true` result means another batch may be useful immediately; it does
    /// not grant the caller permission to monopolize a cooperative executor.
    /// A thread-based runner must yield or otherwise provide a scheduling point
    /// between calls.
    pub fn run_once(&mut self) -> bool {
        saturating_increment(&self.state.shared.run_once_calls);
        let mut did_work = false;
        if let Ok(command) = self.state.shared.commands.try_receive() {
            self.process_or_cancel_command(command);
            did_work = true;
        }
        saturating_increment(&self.state.shared.backend_poll_calls);
        let immediate_repoll = match self.backend.poll() {
            Ok(background_work) => {
                self.last_poll_error = None;
                if background_work {
                    saturating_increment(&self.state.shared.backend_poll_work_batches);
                }
                did_work || background_work
            }
            Err(error) => {
                saturating_increment(&self.state.shared.backend_poll_errors);
                if self.last_poll_error != Some(error) {
                    self.state.shared.publish_event(WifiEvent::Failed(error));
                    self.last_poll_error = Some(error);
                    true
                } else {
                    did_work
                }
            }
        };
        if immediate_repoll {
            saturating_increment(&self.state.shared.immediate_repoll_hints);
        }
        immediate_repoll
    }

    /// Run forever for command-driven backends.
    ///
    /// Backends with timer- or RX-driven [`WifiBackend::poll`] work must call
    /// [`Self::run_once`] from their platform runner so its wait primitive can
    /// cover both command and backend wake sources.
    pub async fn run(mut self) -> ! {
        loop {
            let command = self.state.shared.commands.receive().await;
            self.process_or_cancel_command(command);
        }
    }

    fn process_or_cancel_command(&mut self, command: Command) {
        while let Ok(sequence) = self.state.shared.cancellations.try_receive() {
            if sequence == command.sequence {
                let error = BackendError::new(BackendErrorClass::Cancelled, 0);
                self.state.shared.publish_event(WifiEvent::Failed(error));
                self.state.shared.completion.signal(Completion {
                    sequence,
                    kind: match command.kind {
                        CommandKind::Initialize => CompletionKind::Initialize(Err(error)),
                        CommandKind::Scan(_) => CompletionKind::Scan(Err(error)),
                        CommandKind::Connect(_) => CompletionKind::Connect(Err(error)),
                        CommandKind::Disconnect => CompletionKind::Disconnect(Err(error)),
                    },
                });
                return;
            }
        }
        self.process_command(command);
    }

    fn process_command(&mut self, command: Command) {
        saturating_increment(&self.state.shared.commands_processed);
        let sequence = command.sequence;
        let completion = match command.kind {
            CommandKind::Initialize => {
                let result = self.backend.initialize(&self.config);
                if result.is_ok()
                    && let Some(capabilities) = self.backend.l2_capabilities()
                {
                    self.state.shared.l2_capabilities.publish_once(capabilities);
                }
                self.publish_result(result, WifiEvent::Initialized);
                CompletionKind::Initialize(result)
            }
            CommandKind::Scan(config) => {
                // SAFETY: RadioRunner is unique and processes one command at a
                // time. Completion is signalled only after this borrow ends.
                let output = unsafe { &mut *self.state.shared.scan_results_ptr() };
                let result = self.backend.scan(config, output);
                match result {
                    Ok(outcome) => self.state.shared.publish_event(WifiEvent::ScanCompleted {
                        count: outcome.count,
                        truncated: outcome.truncated,
                    }),
                    Err(error) => self.state.shared.publish_event(WifiEvent::Failed(error)),
                }
                CompletionKind::Scan(result)
            }
            CommandKind::Connect(config) => {
                let result = self.backend.connect(&config);
                match result {
                    Ok(info) => self.state.shared.publish_event(WifiEvent::Connected(info)),
                    Err(error) => self.state.shared.publish_event(WifiEvent::Failed(error)),
                }
                CompletionKind::Connect(result)
            }
            CommandKind::Disconnect => {
                let result = self.backend.disconnect(&self.config);
                self.publish_result(result, WifiEvent::Disconnected { reason: 0 });
                CompletionKind::Disconnect(result)
            }
        };
        self.state.shared.completion.signal(Completion {
            sequence,
            kind: completion,
        });
    }

    fn publish_result(&self, result: Result<(), BackendError>, success: WifiEvent) {
        self.state.shared.publish_event(match result {
            Ok(()) => success,
            Err(error) => WifiEvent::Failed(error),
        });
    }
}

/// L2 data-plane ownership independent of the control backend.
pub struct WifiDevice<D> {
    inner: D,
    l2_capabilities: &'static crate::state::L2CapabilityState,
}

impl<D> WifiDevice<D> {
    /// Snapshot immutable link-layer identity for this radio instance.
    ///
    /// Returns `None` until the instance's backend initialization succeeds.
    pub fn l2_capabilities(&self) -> Option<WifiL2Capabilities> {
        self.l2_capabilities.snapshot()
    }

    /// Return this radio instance's station MAC address after initialization.
    pub fn station_mac_address(&self) -> Option<[u8; 6]> {
        self.l2_capabilities()
            .map(WifiL2Capabilities::station_mac_address)
    }

    /// Borrow the chip L2 device.
    pub fn inner(&self) -> &D {
        &self.inner
    }

    /// Mutably borrow the chip L2 device.
    pub fn inner_mut(&mut self) -> &mut D {
        &mut self.inner
    }

    /// Recover the chip L2 device.
    pub fn into_inner(self) -> D {
        self.inner
    }
}

#[cfg(feature = "smoltcp")]
impl<D: smoltcp::phy::Device> smoltcp::phy::Device for WifiDevice<D> {
    type RxToken<'a>
        = D::RxToken<'a>
    where
        Self: 'a;
    type TxToken<'a>
        = D::TxToken<'a>
    where
        Self: 'a;

    fn receive(
        &mut self,
        timestamp: smoltcp::time::Instant,
    ) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> {
        self.inner.receive(timestamp)
    }

    fn transmit(&mut self, timestamp: smoltcp::time::Instant) -> Option<Self::TxToken<'_>> {
        self.inner.transmit(timestamp)
    }

    fn capabilities(&self) -> smoltcp::phy::DeviceCapabilities {
        self.inner.capabilities()
    }
}

pub(crate) struct Command {
    pub(crate) sequence: u32,
    pub(crate) kind: CommandKind,
}

pub(crate) enum CommandKind {
    Initialize,
    Scan(ScanConfig),
    Connect(StationConfig),
    Disconnect,
}

#[derive(Clone, Copy)]
pub(crate) struct Completion {
    pub(crate) sequence: u32,
    pub(crate) kind: CompletionKind,
}

#[derive(Clone, Copy)]
pub(crate) enum CompletionKind {
    Initialize(Result<(), BackendError>),
    Scan(Result<ScanOutcome, BackendError>),
    Connect(Result<ConnectionInfo, BackendError>),
    Disconnect(Result<(), BackendError>),
    #[cfg(feature = "incremental-backend-experiment")]
    Protocol,
}

#[cfg(test)]
mod tests {
    extern crate std;

    use core::future::Future;
    use core::task::{Context, Poll, Waker};
    use std::boxed::Box;

    use super::*;

    struct MockBackend {
        calls: u8,
        poll_work: bool,
        poll_error: Option<BackendError>,
        initialize_error: Option<BackendError>,
        station_mac_address: [u8; 6],
    }

    impl Default for MockBackend {
        fn default() -> Self {
            Self {
                calls: 0,
                poll_work: false,
                poll_error: None,
                initialize_error: None,
                station_mac_address: [0x02, 1, 2, 3, 4, 5],
            }
        }
    }

    impl WifiBackend for MockBackend {
        fn initialize(&mut self, _: &WifiConfig) -> Result<(), BackendError> {
            self.calls += 1;
            self.initialize_error.map_or(Ok(()), Err)
        }

        fn scan(
            &mut self,
            _: ScanConfig,
            output: &mut [ScanResult],
        ) -> Result<ScanOutcome, BackendError> {
            self.calls += 1;
            output[0] = ScanResult {
                ssid: Ssid::try_from_bytes(b"test-ap").unwrap(),
                bssid: [1, 2, 3, 4, 5, 6],
                frequency_mhz: 2437,
                rssi_dbm: -42,
                security: Security::Wpa2Personal,
                channel: 6,
            };
            Ok(ScanOutcome {
                count: 1,
                truncated: false,
            })
        }

        fn connect(&mut self, config: &StationConfig) -> Result<ConnectionInfo, BackendError> {
            self.calls += 1;
            Ok(ConnectionInfo {
                bssid: config.bssid,
                frequency_mhz: 2437,
            })
        }

        fn disconnect(&mut self, _: &WifiConfig) -> Result<(), BackendError> {
            self.calls += 1;
            Ok(())
        }

        fn l2_capabilities(&self) -> Option<WifiL2Capabilities> {
            WifiL2Capabilities::try_new(self.station_mac_address)
        }

        fn poll(&mut self) -> Result<bool, BackendError> {
            if let Some(error) = self.poll_error {
                Err(error)
            } else {
                Ok(core::mem::take(&mut self.poll_work))
            }
        }
    }

    fn poll<F: Future>(future: core::pin::Pin<&mut F>) -> Poll<F::Output> {
        let waker = Waker::noop();
        future.poll(&mut Context::from_waker(waker))
    }

    #[test]
    fn runner_is_the_only_backend_execution_path() {
        let state = Box::leak(Box::new(RadioState::<4>::new()));
        let radio = init(
            RadioConfig::default(),
            RadioResources {
                backend: MockBackend::default(),
                device: (),
            },
            state,
        )
        .unwrap();
        let RadioParts {
            mut wifi,
            mut runner,
        } = radio.split();
        assert_eq!(wifi.device.l2_capabilities(), None);

        {
            let mut initialize = core::pin::pin!(wifi.controller.initialize());
            assert!(poll(initialize.as_mut()).is_pending());
            assert_eq!(state.shared.commands.len(), 1);
            assert_eq!(state.shared.command_high_water.load(Ordering::Relaxed), 1);
            assert!(runner.run_once());
            assert_eq!(poll(initialize.as_mut()), Poll::Ready(Ok(())));
        }
        assert_eq!(
            wifi.device.l2_capabilities(),
            WifiL2Capabilities::try_new([0x02, 1, 2, 3, 4, 5])
        );
        assert_eq!(
            wifi.device.station_mac_address(),
            Some([0x02, 1, 2, 3, 4, 5])
        );

        let mut results = [ScanResult::EMPTY; 1];
        {
            let mut scan = core::pin::pin!(wifi.controller.scan(
                ScanConfig::new(OperationTimeout::try_from_millis(1_000).unwrap()),
                &mut results,
            ));
            assert!(poll(scan.as_mut()).is_pending());
            assert!(runner.run_once());
            assert_eq!(
                poll(scan.as_mut()),
                Poll::Ready(Ok(ScanOutcome {
                    count: 1,
                    truncated: false,
                }))
            );
        }
        assert_eq!(results[0].ssid.as_bytes(), b"test-ap");
    }

    #[test]
    fn failed_initialization_does_not_publish_l2_capabilities() {
        let state = Box::leak(Box::new(RadioState::<2>::new()));
        let error = BackendError::new(BackendErrorClass::Initialize, 7);
        let radio = init(
            RadioConfig::default(),
            RadioResources {
                backend: MockBackend {
                    initialize_error: Some(error),
                    ..MockBackend::default()
                },
                device: (),
            },
            state,
        )
        .unwrap();
        let RadioParts {
            mut wifi,
            mut runner,
        } = radio.split();

        let mut initialize = core::pin::pin!(wifi.controller.initialize());
        assert!(poll(initialize.as_mut()).is_pending());
        assert!(runner.run_once());
        assert_eq!(
            poll(initialize.as_mut()),
            Poll::Ready(Err(Error::Backend(error)))
        );
        assert_eq!(wifi.device.l2_capabilities(), None);
        assert_eq!(wifi.device.station_mac_address(), None);
    }

    #[test]
    fn l2_capabilities_are_owned_by_each_radio_instance() {
        let state_a = Box::leak(Box::new(RadioState::<2>::new()));
        let state_b = Box::leak(Box::new(RadioState::<2>::new()));
        let mac_a = [0x02, 1, 1, 1, 1, 1];
        let mac_b = [0x02, 2, 2, 2, 2, 2];
        let radio_a = init(
            RadioConfig::default(),
            RadioResources {
                backend: MockBackend {
                    station_mac_address: mac_a,
                    ..MockBackend::default()
                },
                device: (),
            },
            state_a,
        )
        .unwrap();
        let radio_b = init(
            RadioConfig::default(),
            RadioResources {
                backend: MockBackend {
                    station_mac_address: mac_b,
                    ..MockBackend::default()
                },
                device: (),
            },
            state_b,
        )
        .unwrap();
        let RadioParts {
            wifi: mut wifi_a,
            runner: mut runner_a,
        } = radio_a.split();
        let RadioParts {
            wifi: mut wifi_b,
            runner: mut runner_b,
        } = radio_b.split();

        let mut initialize_a = core::pin::pin!(wifi_a.controller.initialize());
        let mut initialize_b = core::pin::pin!(wifi_b.controller.initialize());
        assert!(poll(initialize_a.as_mut()).is_pending());
        assert!(poll(initialize_b.as_mut()).is_pending());
        assert!(runner_a.run_once());
        assert!(runner_b.run_once());
        assert_eq!(poll(initialize_a.as_mut()), Poll::Ready(Ok(())));
        assert_eq!(poll(initialize_b.as_mut()), Poll::Ready(Ok(())));
        assert_eq!(wifi_a.device.station_mac_address(), Some(mac_a));
        assert_eq!(wifi_b.device.station_mac_address(), Some(mac_b));
    }

    #[test]
    fn bounded_events_drop_the_oldest_and_report_overflow() {
        let state = Box::leak(Box::new(RadioState::<1>::new()));
        let radio = init(
            RadioConfig::default(),
            RadioResources {
                backend: MockBackend::default(),
                device: (),
            },
            state,
        )
        .unwrap();
        let RadioParts {
            mut wifi,
            mut runner,
        } = radio.split();

        for _ in 0..2 {
            let mut initialize = core::pin::pin!(wifi.controller.initialize());
            assert!(poll(initialize.as_mut()).is_pending());
            assert!(runner.run_once());
            assert_eq!(poll(initialize.as_mut()), Poll::Ready(Ok(())));
        }
        assert_eq!(
            wifi.controller.event_diagnostics(),
            EventDiagnostics {
                capacity: 1,
                accepted: 2,
                consumed: 0,
                pending: 1,
                high_water: 1,
                dropped: 1,
            }
        );
    }

    #[test]
    fn runner_advances_background_work_without_a_command() {
        let state = Box::leak(Box::new(RadioState::<2>::new()));
        let radio = init(
            RadioConfig::default(),
            RadioResources {
                backend: MockBackend {
                    poll_work: true,
                    ..MockBackend::default()
                },
                device: (),
            },
            state,
        )
        .unwrap();
        let mut runner = radio.split().runner;

        assert!(runner.run_once());
        assert!(!runner.run_once());
    }

    #[test]
    fn repeated_background_error_publishes_one_event() {
        let state = Box::leak(Box::new(RadioState::<2>::new()));
        let error = BackendError::new(BackendErrorClass::Other, 0x55);
        let radio = init(
            RadioConfig::default(),
            RadioResources {
                backend: MockBackend {
                    poll_error: Some(error),
                    ..MockBackend::default()
                },
                device: (),
            },
            state,
        )
        .unwrap();
        let RadioParts {
            mut wifi,
            mut runner,
        } = radio.split();

        assert!(runner.run_once());
        assert!(!runner.run_once());
        assert_eq!(
            wifi.controller.event_diagnostics(),
            EventDiagnostics {
                capacity: 2,
                accepted: 1,
                consumed: 0,
                pending: 1,
                high_water: 1,
                dropped: 0,
            }
        );
        {
            let mut event = core::pin::pin!(wifi.controller.next_event());
            assert_eq!(poll(event.as_mut()), Poll::Ready(WifiEvent::Failed(error)));
        }
        assert_eq!(
            wifi.controller.event_diagnostics(),
            EventDiagnostics {
                capacity: 2,
                accepted: 1,
                consumed: 1,
                pending: 0,
                high_water: 1,
                dropped: 0,
            }
        );
    }

    #[test]
    fn blocking_runner_diagnostics_count_bounded_work() {
        let state = Box::leak(Box::new(RadioState::<2>::new()));
        let error = BackendError::new(BackendErrorClass::Other, 0x55);
        let radio = init(
            RadioConfig::default(),
            RadioResources {
                backend: MockBackend {
                    poll_work: true,
                    ..MockBackend::default()
                },
                device: (),
            },
            state,
        )
        .unwrap();
        let RadioParts {
            mut wifi,
            mut runner,
        } = radio.split();

        {
            let mut initialize = core::pin::pin!(wifi.controller.initialize());
            assert!(poll(initialize.as_mut()).is_pending());
            assert!(runner.run_once());
            assert_eq!(poll(initialize.as_mut()), Poll::Ready(Ok(())));
        }
        assert!(!runner.run_once());

        runner.backend.poll_error = Some(error);
        assert!(runner.run_once());
        assert!(!runner.run_once());

        assert_eq!(
            wifi.controller.blocking_runner_diagnostics(),
            BlockingRunnerDiagnostics {
                command_queue_pending: 0,
                command_queue_high_water: 1,
                run_once_calls: 4,
                commands_processed: 1,
                backend_poll_calls: 4,
                backend_poll_work_batches: 1,
                backend_poll_errors: 2,
                immediate_repoll_hints: 2,
            }
        );
    }

    #[test]
    fn cancelled_control_future_cannot_poison_the_next_command() {
        let state = Box::leak(Box::new(RadioState::<2>::new()));
        let radio = init(
            RadioConfig::default(),
            RadioResources {
                backend: MockBackend::default(),
                device: (),
            },
            state,
        )
        .unwrap();
        let RadioParts {
            mut wifi,
            mut runner,
        } = radio.split();

        {
            let mut cancelled = core::pin::pin!(wifi.controller.initialize());
            assert!(poll(cancelled.as_mut()).is_pending());
        }
        assert!(runner.run_once());
        assert_eq!(runner.backend.calls, 0);

        let mut next = core::pin::pin!(wifi.controller.initialize());
        assert!(poll(next.as_mut()).is_pending());
        assert!(runner.run_once());
        assert_eq!(runner.backend.calls, 1);
        assert_eq!(poll(next.as_mut()), Poll::Ready(Ok(())));
    }

    #[test]
    fn validated_configuration_rejects_invalid_inputs() {
        assert!(Ssid::try_from_bytes(b"").is_none());
        assert!(Ssid::try_from_bytes(&[b'x'; 33]).is_none());
        assert!(Passphrase::try_from_ascii(b"short").is_none());
        assert!(Passphrase::try_from_ascii(b"testtest").is_some());
        assert!(OperationTimeout::try_from_millis(0).is_none());
        assert!(BackendTimeout::try_from_millis(0).is_none());
        assert_eq!(OperationTimeout::try_from_millis(1).unwrap().as_millis(), 1);
        assert_eq!(BackendTimeout::try_from_millis(1).unwrap().as_millis(), 1);
        assert!(WifiL2Capabilities::try_new([0; 6]).is_none());
        assert!(WifiL2Capabilities::try_new([1, 2, 3, 4, 5, 6]).is_none());
        assert_eq!(
            WifiL2Capabilities::try_new([0x02, 1, 2, 3, 4, 5])
                .unwrap()
                .station_mac_address(),
            [0x02, 1, 2, 3, 4, 5]
        );
    }

    #[test]
    fn wpa3_config_requires_wpa3_scan_and_implies_required_pmf() {
        let result = ScanResult {
            ssid: Ssid::try_from_bytes(b"wpa3-ap").unwrap(),
            bssid: [1, 2, 3, 4, 5, 6],
            frequency_mhz: 5180,
            rssi_dbm: -38,
            security: Security::Wpa3Personal,
            channel: 36,
        };
        let config = StationConfig::wpa3_personal(
            &result,
            Passphrase::try_from_ascii(b"testtest").unwrap(),
            SaePwe::Both,
            OperationTimeout::try_from_millis(10_000).unwrap(),
        )
        .unwrap();
        assert_eq!(
            config.security(),
            PersonalSecurity::Wpa3 {
                sae_pwe: SaePwe::Both
            }
        );
        assert_eq!(
            config.security().management_frame_protection(),
            ManagementFrameProtection::Required
        );
    }

    #[test]
    fn transition_scan_requires_an_explicit_personal_mode_choice() {
        let result = ScanResult {
            ssid: Ssid::try_from_bytes(b"transition-ap").unwrap(),
            bssid: [1, 2, 3, 4, 5, 6],
            frequency_mhz: 5180,
            rssi_dbm: -38,
            security: Security::Wpa2Wpa3PersonalTransition,
            channel: 36,
        };

        let wpa2 = StationConfig::wpa2_personal(
            &result,
            Passphrase::try_from_ascii(b"testtest").unwrap(),
            OperationTimeout::try_from_millis(10_000).unwrap(),
        )
        .unwrap();
        assert_eq!(wpa2.security(), PersonalSecurity::Wpa2);

        let wpa3 = StationConfig::wpa3_personal(
            &result,
            Passphrase::try_from_ascii(b"testtest").unwrap(),
            SaePwe::Both,
            OperationTimeout::try_from_millis(10_000).unwrap(),
        )
        .unwrap();
        assert_eq!(
            wpa3.security(),
            PersonalSecurity::Wpa3 {
                sae_pwe: SaePwe::Both
            }
        );
    }
}