wlansoftmac_rust/
lib.rs

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
// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use anyhow::{format_err, Error};
use fidl::endpoints::{ProtocolMarker, Proxy};
use fuchsia_async::{MonotonicDuration, Task};
use fuchsia_inspect::Inspector;
use futures::channel::mpsc;
use futures::channel::oneshot::{self, Canceled};
use futures::{Future, FutureExt, StreamExt};
use std::pin::Pin;
use tracing::{error, info, warn};
use wlan_ffi_transport::completers::Completer;
use wlan_ffi_transport::{EthernetTx, WlanRx};
use wlan_fidl_ext::{ResponderExt, SendResultExt, WithName};
use wlan_mlme::device::DeviceOps;
use wlan_mlme::{DriverEvent, DriverEventSink};
use wlan_sme::serve::create_sme;
use {
    fidl_fuchsia_wlan_common as fidl_common, fidl_fuchsia_wlan_sme as fidl_sme,
    fidl_fuchsia_wlan_softmac as fidl_softmac, fuchsia_inspect_auto_persist as auto_persist,
    wlan_trace as wtrace,
};

const INSPECT_VMO_SIZE_BYTES: usize = 1000 * 1024;

/// Run the bridged wlansoftmac driver composed of the following servers:
///
///   - WlanSoftmacIfcBridge server
///   - MLME server
///   - SME server
///
/// The WlanSoftmacIfcBridge server future executes on a parallel thread because otherwise
/// synchronous calls from the MLME server into the vendor driver could deadlock if the vendor
/// driver calls a WlanSoftmacIfcBridge method before returning from a synchronous call. For
/// example, when the MLME server synchronously calls WlanSoftmac.StartActiveScan(), the vendor
/// driver may call WlanSoftmacIfc.NotifyScanComplete() before returning from
/// WlanSoftmac.StartActiveScan(). This can occur when the scan request results in immediate
/// cancellation despite the request having valid arguments.
///
/// This function calls `start_completer()` when MLME initialization completes successfully, and
/// will return in one of four cases:
///
///   - An error occurred during initialization.
///   - An error occurred while running.
///   - An error occurred during shutdown.
///   - Shutdown completed successfully.
///
/// If an error occurs during the bridge driver's initialization, `start_completer()` will not be
/// called.
pub async fn start_and_serve<F, D: DeviceOps + 'static>(
    start_completer: Completer<F>,
    device: D,
) -> Result<(), zx::Status>
where
    F: FnOnce(zx::sys::zx_status_t) + 'static,
{
    wtrace::duration_begin_scope!(c"rust_driver::start_and_serve");
    let (driver_event_sink, driver_event_stream) = DriverEventSink::new();

    let (mlme_init_sender, mlme_init_receiver) = oneshot::channel();
    let StartedDriver { softmac_ifc_bridge_request_stream, mlme, sme } =
        match start(mlme_init_sender, driver_event_sink.clone(), driver_event_stream, device).await
        {
            Err(status) => {
                start_completer.reply(Err(status));
                return Err(status);
            }
            Ok(x) => x,
        };

    start_completer.reply(Ok(()));

    serve(mlme_init_receiver, driver_event_sink, softmac_ifc_bridge_request_stream, mlme, sme).await
}

struct StartedDriver<Mlme, Sme> {
    pub softmac_ifc_bridge_request_stream: fidl_softmac::WlanSoftmacIfcBridgeRequestStream,
    pub mlme: Mlme,
    pub sme: Sme,
}

/// Start the bridged wlansoftmac driver by creating components to run two futures:
///
///   - MLME server
///   - SME server
///
/// This function will use the provided |device| to make various calls into the vendor driver
/// necessary to configure and create the components to run the futures.
async fn start<D: DeviceOps + 'static>(
    mlme_init_sender: oneshot::Sender<()>,
    driver_event_sink: DriverEventSink,
    driver_event_stream: mpsc::UnboundedReceiver<DriverEvent>,
    mut device: D,
) -> Result<
    StartedDriver<
        Pin<Box<dyn Future<Output = Result<(), Error>>>>,
        Pin<Box<impl Future<Output = Result<(), Error>>>>,
    >,
    zx::Status,
> {
    wtrace::duration!(c"rust_driver::start");

    let (softmac_ifc_bridge_proxy, softmac_ifc_bridge_request_stream) =
        fidl::endpoints::create_proxy_and_stream::<fidl_softmac::WlanSoftmacIfcBridgeMarker>();

    // Bootstrap USME
    let BootstrappedGenericSme { generic_sme_request_stream, legacy_privacy_support, inspector } =
        bootstrap_generic_sme(&mut device, driver_event_sink, softmac_ifc_bridge_proxy).await?;

    info!("Querying device information...");

    // Make a series of queries to gather device information from the vendor driver.
    let softmac_info = device.wlan_softmac_query_response().await?;
    let sta_addr = softmac_info.sta_addr;
    let device_info = match wlan_mlme::mlme_device_info_from_softmac(softmac_info) {
        Ok(info) => info,
        Err(e) => {
            error!("Failed to get MLME device info: {}", e);
            return Err(zx::Status::INTERNAL);
        }
    };

    let mac_sublayer_support = device.mac_sublayer_support().await?;
    let mac_implementation_type = &mac_sublayer_support.device.mac_implementation_type;
    if *mac_implementation_type != fidl_common::MacImplementationType::Softmac {
        error!("Wrong MAC implementation type: {:?}", mac_implementation_type);
        return Err(zx::Status::INTERNAL);
    }
    let security_support = device.security_support().await?;
    let spectrum_management_support = device.spectrum_management_support().await?;

    info!("Querying complete!");

    // TODO(https://fxbug.dev/42064968): Get persistence working by adding the appropriate configs
    //                         in *.cml files
    let (persistence_proxy, _persistence_server_end) =
        fidl::endpoints::create_proxy::<fidl_fuchsia_diagnostics_persist::DataPersistenceMarker>();
    let (persistence_req_sender, _persistence_req_forwarder_fut) =
        auto_persist::create_persistence_req_sender(persistence_proxy);

    let config = wlan_sme::Config {
        wep_supported: legacy_privacy_support.wep_supported,
        wpa1_supported: legacy_privacy_support.wpa1_supported,
    };

    // TODO(https://fxbug.dev/42077094): The MLME event stream should be moved out of DeviceOps
    // entirely.
    let mlme_event_stream = match device.take_mlme_event_stream() {
        Some(mlme_event_stream) => mlme_event_stream,
        None => {
            error!("Failed to take MLME event stream.");
            return Err(zx::Status::INTERNAL);
        }
    };

    // Create an SME future to serve
    let (mlme_request_stream, sme) = match create_sme(
        config,
        mlme_event_stream,
        &device_info,
        mac_sublayer_support,
        security_support,
        spectrum_management_support,
        inspector,
        persistence_req_sender,
        generic_sme_request_stream,
    ) {
        Ok((mlme_request_stream, sme)) => (mlme_request_stream, sme),
        Err(e) => {
            error!("Failed to create sme: {}", e);
            return Err(zx::Status::INTERNAL);
        }
    };

    // Create an MLME future to serve
    let mlme: Pin<Box<dyn Future<Output = Result<(), Error>>>> = match device_info.role {
        fidl_common::WlanMacRole::Client => {
            info!("Running wlansoftmac with client role");
            let config = wlan_mlme::client::ClientConfig {
                ensure_on_channel_time: MonotonicDuration::from_millis(500).into_nanos(),
            };
            Box::pin(wlan_mlme::mlme_main_loop::<wlan_mlme::client::ClientMlme<D>>(
                mlme_init_sender,
                config,
                device,
                mlme_request_stream,
                driver_event_stream,
            ))
        }
        fidl_common::WlanMacRole::Ap => {
            info!("Running wlansoftmac with AP role");
            let sta_addr = match sta_addr {
                Some(sta_addr) => sta_addr,
                None => {
                    error!("Driver provided no STA address.");
                    return Err(zx::Status::INTERNAL);
                }
            };
            let config = ieee80211::Bssid::from(sta_addr);
            Box::pin(wlan_mlme::mlme_main_loop::<wlan_mlme::ap::Ap<D>>(
                mlme_init_sender,
                config,
                device,
                mlme_request_stream,
                driver_event_stream,
            ))
        }
        unsupported => {
            error!("Unsupported mac role: {:?}", unsupported);
            return Err(zx::Status::INTERNAL);
        }
    };

    Ok(StartedDriver { softmac_ifc_bridge_request_stream, mlme, sme })
}

/// Await on futures hosting the following three servers:
///
///   - WlanSoftmacIfcBridge server
///   - MLME server
///   - SME server
///
/// The WlanSoftmacIfcBridge server runs on a parallel thread but will be shut down before this
/// function returns. This is true even if this function exits with an error.
///
/// Upon receiving a DriverEvent::Stop, the MLME server will shut down first. Then this function
/// will await the completion of WlanSoftmacIfcBridge server and SME server. Both will shut down as
/// a consequence of MLME server shut down.
async fn serve(
    mlme_init_receiver: oneshot::Receiver<()>,
    driver_event_sink: DriverEventSink,
    softmac_ifc_bridge_request_stream: fidl_softmac::WlanSoftmacIfcBridgeRequestStream,
    mlme: Pin<Box<dyn Future<Output = Result<(), Error>>>>,
    sme: Pin<Box<impl Future<Output = Result<(), Error>>>>,
) -> Result<(), zx::Status> {
    wtrace::duration_begin_scope!(c"rust_driver::serve");

    // Create a oneshot::channel to signal to this executor when WlanSoftmacIfcBridge
    // server exits.
    let (bridge_exit_sender, bridge_exit_receiver) = oneshot::channel();
    // Spawn a Task to host the WlanSoftmacIfcBridge server.
    let bridge = Task::local(async move {
        let _: Result<(), ()> = bridge_exit_sender
            .send(
                serve_wlan_softmac_ifc_bridge(driver_event_sink, softmac_ifc_bridge_request_stream)
                    .await,
            )
            .map_err(|result| {
                error!("Failed to send serve_wlan_softmac_ifc_bridge() result: {:?}", result)
            });
    });

    let mut mlme = mlme.fuse();
    let mut sme = sme.fuse();

    // oneshot::Receiver implements FusedFuture incorrectly, so we must call .fuse()
    // to get the right behavior in the select!().
    //
    // See https://github.com/rust-lang/futures-rs/issues/2455 for more details.
    let mut bridge_exit_receiver = bridge_exit_receiver.fuse();
    let mut mlme_init_receiver = mlme_init_receiver.fuse();

    info!("Starting MLME and waiting on MLME initialization to complete...");
    // Run the MLME server and wait for the MLME to signal initialization completion.
    //
    // The order of the futures in this select is not arbitrary. During initialization, there is
    // an edge case where MLME could be stopped before initialization completes. By polling
    // the MLME future first, we can unit test handling this edge case by completing the MLME
    // future and initialization, in that order, and then polling the future returned by
    // serve() (i.e., this function).
    {
        wtrace::duration_begin_scope!(c"initialize MLME");
        futures::select! {
            mlme_result = mlme => {
                match mlme_result {
                    Err(e) => {
                        error!("MLME future completed with error during initialization: {:?}", e);
                        std::mem::drop(bridge);
                        return Err(zx::Status::INTERNAL);
                    }
                    Ok(()) => {

                        // It's possible MLME received a DriverEvent::Stop and returned after
                        // signaling initialization completed and before mlme_init_receiver being
                        // polled. If that's the case, then log a warning that SME never started and
                        // return Ok. Exiting the server in this way should be considered okay
                        // because MLME signaled initialization completed and exited successfully.
                        match mlme_init_receiver.now_or_never() {
                            None | Some(Err(Canceled)) => {
                                error!("MLME future completed before signaling initialization complete.");
                                std::mem::drop(bridge);
                                return Err(zx::Status::INTERNAL);
                            }
                            Some(Ok(())) => {
                                warn!("SME never started. MLME future completed successfully just after initialization.");
                                std::mem::drop(bridge);
                                return Ok(());
                            }
                        }
                    }
                }
            }
            init_result = mlme_init_receiver => {
                match init_result {
                    Ok(()) => (),
                    Err(e) => {
                        error!("MLME dropped the initialization signaler: {}", e);
                        std::mem::drop(bridge);
                        return Err(zx::Status::INTERNAL);
                    }
                }
            },
        }
    }

    info!("Starting SME and WlanSoftmacIfc servers...");

    // Run the SME and MLME servers.
    {
        wtrace::duration_begin_scope!(c"run MLME and SME");
        // This loop-select has two phases.
        //
        // In the first phase, all three futures are running. The first phase will break
        // the loop with an error if any of the following events occurs:
        //
        //   - SME future completes before MLME.
        //   - Any future completes with an error.
        //
        // If the bridge_exit_receiver completes successfully, the MLME and SME futures continue.
        // It's possible for bridge_exit_receiver to complete before MLME because
        // the bridge server exits upon receiving the StopBridgedDriver message while the MLME
        // future consumes the StopBridgedDriver message and responds asynchronously.
        //
        // The first phase ends successfully only if the MLME future completes successfully.
        //
        // The second phase runs the SME future and, if not complete, the
        // bridge_exit_receiver future. The second phase ends with an error if either the
        // SME future or bridge_exit_receiver future return an error.  Otherwise, the
        // second phase ends successfully.
        let mut mlme_future_complete = false;
        loop {
            futures::select! {
                mlme_result = mlme => {
                    match mlme_result {
                        Ok(()) => {
                            info!("MLME shut down gracefully.");
                            mlme_future_complete = true;
                        },
                        Err(e) => {
                            error!("MLME shut down with error: {}", e);
                            break Err(zx::Status::INTERNAL)
                        }
                    }
                }
                bridge_result = bridge_exit_receiver => {
                    // We expect the bridge to shut itself down immediately upon receiving a
                    // StopBridgedDriver message, so it's often the case that the bridge task
                    // will exit before MLME. When the bridge task completes first, both
                    // the `mlme` and `sme` futures should continue to run.
                    match bridge_result {
                        Err(Canceled) => {
                            error!("SoftmacIfcBridge result sender dropped unexpectedly.");
                            break Err(zx::Status::INTERNAL)
                        }
                        Ok(Err(e)) => {
                            error!("SoftmacIfcBridge server shut down with error: {}", e);
                            break Err(zx::Status::INTERNAL)
                        }
                        Ok(Ok(())) => info!("SoftmacIfcBridge server shut down gracefully"),
                    }
                }
                sme_result = sme => {
                    if mlme_future_complete {
                        match sme_result {
                            Err(e) => {
                                error!("SME shut down with error: {}", e);
                                break Err(zx::Status::INTERNAL)
                            }
                            Ok(()) => info!("SME shut down gracefully"),
                        }
                    } else {
                        error!("SME shut down before MLME: {:?}", sme_result);
                        break Err(zx::Status::INTERNAL)
                    }
                }
                complete => break Ok(())
            }
        }
    }
}

struct BootstrappedGenericSme {
    pub generic_sme_request_stream: fidl_sme::GenericSmeRequestStream,
    pub legacy_privacy_support: fidl_sme::LegacyPrivacySupport,
    pub inspector: Inspector,
}

/// Call WlanSoftmac.Start() to retrieve the server end of UsmeBootstrap channel and wait
/// for a UsmeBootstrap.Start() message to provide the server end of a GenericSme channel.
///
/// Any errors encountered in this function are fatal for the wlansoftmac driver. Failure to
/// bootstrap GenericSme request stream will result in a driver no other component can communicate
/// with.
async fn bootstrap_generic_sme<D: DeviceOps>(
    device: &mut D,
    driver_event_sink: DriverEventSink,
    softmac_ifc_bridge_proxy: fidl_softmac::WlanSoftmacIfcBridgeProxy,
) -> Result<BootstrappedGenericSme, zx::Status> {
    wtrace::duration!(c"rust_driver::bootstrap_generic_sme");
    info!("Bootstrapping GenericSme...");

    let ifc_bridge = softmac_ifc_bridge_proxy.into_client_end().map_err(|_| {
        error!(
            "Failed to convert {} into client end.",
            fidl_softmac::WlanSoftmacIfcBridgeMarker::DEBUG_NAME
        );
        zx::Status::INTERNAL
    })?;

    // Calling WlanSoftmac.Start() indicates to the vendor driver that this driver (wlansoftmac) is
    // ready to receive WlanSoftmacIfc messages. wlansoftmac will buffer all WlanSoftmacIfc messages
    // in an mpsc::UnboundedReceiver<DriverEvent> sink until the MLME server drains them.
    let usme_bootstrap_channel_via_iface_creation = match device
        .start(
            ifc_bridge,
            EthernetTx::new(Box::new(driver_event_sink.clone())),
            WlanRx::new(Box::new(driver_event_sink)),
        )
        .await
    {
        Ok(channel) => channel,
        Err(status) => {
            error!("Failed to receive a UsmeBootstrap handle: {}", status);
            return Err(status);
        }
    };
    info!("Bootstrap complete!");

    let server = fidl::endpoints::ServerEnd::<fidl_sme::UsmeBootstrapMarker>::new(
        usme_bootstrap_channel_via_iface_creation,
    );
    let mut usme_bootstrap_stream = server.into_stream();

    let (generic_sme_server, legacy_privacy_support, responder) =
        match usme_bootstrap_stream.next().await {
            Some(Ok(fidl_sme::UsmeBootstrapRequest::Start {
                generic_sme_server,
                legacy_privacy_support,
                responder,
                ..
            })) => (generic_sme_server, legacy_privacy_support, responder),
            Some(Err(e)) => {
                error!("Received an error on USME bootstrap request stream: {}", e);
                return Err(zx::Status::BAD_STATE);
            }
            None => {
                // This is always an error because the SME server should not drop
                // the USME client endpoint until MLME shut down first.
                error!("USME bootstrap stream terminated unexpectedly");
                return Err(zx::Status::BAD_STATE);
            }
        };

    let inspector =
        Inspector::new(fuchsia_inspect::InspectorConfig::default().size(INSPECT_VMO_SIZE_BYTES));

    let inspect_vmo = match inspector.duplicate_vmo() {
        Some(vmo) => vmo,
        None => {
            error!("Failed to duplicate inspect VMO");
            return Err(zx::Status::INTERNAL);
        }
    };
    if let Err(e) = responder.send(inspect_vmo).into() {
        error!("Failed to respond to UsmeBootstrap.Start(): {}", e);
        return Err(zx::Status::INTERNAL);
    }
    let generic_sme_request_stream = generic_sme_server.into_stream();

    Ok(BootstrappedGenericSme { generic_sme_request_stream, legacy_privacy_support, inspector })
}

async fn serve_wlan_softmac_ifc_bridge(
    driver_event_sink: DriverEventSink,
    mut softmac_ifc_bridge_request_stream: fidl_softmac::WlanSoftmacIfcBridgeRequestStream,
) -> Result<(), anyhow::Error> {
    loop {
        let request = match softmac_ifc_bridge_request_stream.next().await {
            Some(Ok(request)) => request,
            Some(Err(e)) => {
                return Err(format_err!("WlanSoftmacIfcBridge stream failed: {}", e));
            }
            None => {
                return Err(format_err!(
                    "WlanSoftmacIfcBridge stream terminated unexpectedly by client"
                ));
            }
        };
        match request {
            fidl_softmac::WlanSoftmacIfcBridgeRequest::ReportTxResult { tx_result, responder } => {
                let responder = driver_event_sink.unbounded_send_or_respond(
                    DriverEvent::TxResultReport { tx_result },
                    responder,
                    (),
                )?;
                responder.send().format_send_err_with_context("ReportTxResult")?;
            }
            fidl_softmac::WlanSoftmacIfcBridgeRequest::NotifyScanComplete {
                payload,
                responder,
            } => {
                let ((status, scan_id), responder) = responder.unpack_fields_or_respond((
                    payload.status.with_name("status"),
                    payload.scan_id.with_name("scan_id"),
                ))?;
                let status = zx::Status::from_raw(status);
                let responder = driver_event_sink.unbounded_send_or_respond(
                    DriverEvent::ScanComplete { status, scan_id },
                    responder,
                    (),
                )?;
                responder.send().format_send_err_with_context("NotifyScanComplete")?;
            }
            fidl_softmac::WlanSoftmacIfcBridgeRequest::StopBridgedDriver { responder } => {
                if let Err(e) = driver_event_sink.unbounded_send(DriverEvent::Stop { responder }) {
                    let error_string = e.to_string();
                    let event = e.into_inner();
                    let e = format_err!("Failed to queue {}: {}", event, error_string);
                    let DriverEvent::Stop { responder } = event else {
                        unreachable!();
                    };
                    responder.send().format_send_err_with_context("StopBridgedDriver")?;
                    return Err(e);
                }
                return Ok(());
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use anyhow::format_err;
    use diagnostics_assertions::assert_data_tree;
    use fuchsia_async::TestExecutor;
    use fuchsia_inspect::InspectorConfig;
    use futures::stream::FuturesUnordered;
    use futures::task::Poll;
    use std::pin::pin;
    use test_case::test_case;
    use wlan_common::assert_variant;
    use wlan_mlme::device::test_utils::{FakeDevice, FakeDeviceConfig};
    use zx::Vmo;

    struct BootstrapGenericSmeTestHarness {
        _softmac_ifc_bridge_request_stream: fidl_softmac::WlanSoftmacIfcBridgeRequestStream,
    }

    // We could implement BootstrapGenericSmeTestHarness::new() instead of a macro, but doing so requires
    // pinning the FakeDevice and WlanSoftmacIfcProtocol (and its associated DriverEventSink). While the
    // pinning itself is feasible, it leads to a complex harness implementation that outweighs the benefit
    // of using a harness to begin with.
    macro_rules! make_bootstrap_generic_sme_test_harness {
        (&mut $fake_device:ident, $driver_event_sink:ident $(,)?) => {{
            let (softmac_ifc_bridge_proxy, _softmac_ifc_bridge_request_stream) =
                fidl::endpoints::create_proxy_and_stream::<fidl_softmac::WlanSoftmacIfcBridgeMarker>();
            (
                Box::pin(bootstrap_generic_sme(
                    &mut $fake_device,
                    $driver_event_sink,
                    softmac_ifc_bridge_proxy,
                )),
                BootstrapGenericSmeTestHarness {
                    _softmac_ifc_bridge_request_stream,
                }
            )
        }};
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn bootstrap_generic_sme_fails_to_retrieve_usme_bootstrap_handle() {
        let (mut fake_device, _fake_device_state) = FakeDevice::new_with_config(
            FakeDeviceConfig::default().with_mock_start_result(Err(zx::Status::INTERRUPTED_RETRY)),
        )
        .await;
        let (driver_event_sink, _driver_event_stream) = DriverEventSink::new();

        let (mut bootstrap_generic_sme_fut, _harness) =
            make_bootstrap_generic_sme_test_harness!(&mut fake_device, driver_event_sink);
        match TestExecutor::poll_until_stalled(&mut bootstrap_generic_sme_fut).await {
            Poll::Ready(Err(zx::Status::INTERRUPTED_RETRY)) => (),
            Poll::Ready(Err(status)) => panic!("Failed with wrong status: {}", status),
            Poll::Ready(Ok(_)) => panic!("Succeeded unexpectedly"),
            Poll::Pending => panic!("bootstrap_generic_sme() unexpectedly stalled"),
        }
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn boostrap_generic_sme_fails_on_error_from_bootstrap_stream() {
        let (mut fake_device, fake_device_state) =
            FakeDevice::new_with_config(FakeDeviceConfig::default()).await;
        let (driver_event_sink, _driver_event_stream) = DriverEventSink::new();

        let (mut bootstrap_generic_sme_fut, _harness) =
            make_bootstrap_generic_sme_test_harness!(&mut fake_device, driver_event_sink);
        assert!(matches!(
            TestExecutor::poll_until_stalled(&mut bootstrap_generic_sme_fut).await,
            Poll::Pending
        ));

        // Write an invalid FIDL message to the USME bootstrap channel.
        let usme_bootstrap_channel =
            fake_device_state.lock().usme_bootstrap_client_end.take().unwrap().into_channel();
        usme_bootstrap_channel.write(&[], &mut []).unwrap();

        assert!(matches!(
            TestExecutor::poll_until_stalled(&mut bootstrap_generic_sme_fut).await,
            Poll::Ready(Err(zx::Status::BAD_STATE))
        ));
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn boostrap_generic_sme_fails_on_closed_bootstrap_stream() {
        let (mut fake_device, fake_device_state) =
            FakeDevice::new_with_config(FakeDeviceConfig::default()).await;
        let (driver_event_sink, _driver_event_stream) = DriverEventSink::new();

        let (mut bootstrap_generic_sme_fut, _harness) =
            make_bootstrap_generic_sme_test_harness!(&mut fake_device, driver_event_sink);
        assert!(matches!(
            TestExecutor::poll_until_stalled(&mut bootstrap_generic_sme_fut).await,
            Poll::Pending
        ));

        // Drop the client end of USME bootstrap channel.
        let _ = fake_device_state.lock().usme_bootstrap_client_end.take().unwrap();

        assert!(matches!(
            TestExecutor::poll_until_stalled(&mut bootstrap_generic_sme_fut).await,
            Poll::Ready(Err(zx::Status::BAD_STATE))
        ));
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn boostrap_generic_sme_succeeds() {
        let (mut fake_device, fake_device_state) =
            FakeDevice::new_with_config(FakeDeviceConfig::default()).await;
        let (driver_event_sink, _driver_event_stream) = DriverEventSink::new();

        let (mut bootstrap_generic_sme_fut, _harness) =
            make_bootstrap_generic_sme_test_harness!(&mut fake_device, driver_event_sink);
        assert!(matches!(
            TestExecutor::poll_until_stalled(&mut bootstrap_generic_sme_fut).await,
            Poll::Pending
        ));

        let usme_bootstrap_proxy =
            fake_device_state.lock().usme_bootstrap_client_end.take().unwrap().into_proxy();

        let sent_legacy_privacy_support =
            fidl_sme::LegacyPrivacySupport { wep_supported: false, wpa1_supported: false };
        let (generic_sme_proxy, generic_sme_server) =
            fidl::endpoints::create_proxy::<fidl_sme::GenericSmeMarker>();
        let inspect_vmo_fut =
            usme_bootstrap_proxy.start(generic_sme_server, &sent_legacy_privacy_support);
        let mut inspect_vmo_fut = pin!(inspect_vmo_fut);
        assert!(matches!(
            TestExecutor::poll_until_stalled(&mut inspect_vmo_fut).await,
            Poll::Pending
        ));

        let BootstrappedGenericSme {
            mut generic_sme_request_stream,
            legacy_privacy_support: received_legacy_privacy_support,
            inspector,
        } = match TestExecutor::poll_until_stalled(&mut bootstrap_generic_sme_fut).await {
            Poll::Pending => panic!("bootstrap_generic_sme_fut() did not complete!"),
            Poll::Ready(x) => x.unwrap(),
        };
        let inspect_vmo = match TestExecutor::poll_until_stalled(&mut inspect_vmo_fut).await {
            Poll::Pending => panic!("Failed to receive an inspect VMO."),
            Poll::Ready(x) => x.unwrap(),
        };

        // Send a GenericSme.Query() to check the generic_sme_proxy
        // and generic_sme_stream are connected.
        let query_fut = generic_sme_proxy.query();
        let mut query_fut = pin!(query_fut);
        assert!(matches!(TestExecutor::poll_until_stalled(&mut query_fut).await, Poll::Pending));
        let next_generic_sme_request_fut = generic_sme_request_stream.next();
        let mut next_generic_sme_request_fut = pin!(next_generic_sme_request_fut);
        assert!(matches!(
            TestExecutor::poll_until_stalled(&mut next_generic_sme_request_fut).await,
            Poll::Ready(Some(Ok(fidl_sme::GenericSmeRequest::Query { .. })))
        ));

        assert_eq!(received_legacy_privacy_support, sent_legacy_privacy_support);

        // Add a child node through the bootstrapped inspector and verify the node appears inspect_vmo.
        let returned_inspector = Inspector::new(InspectorConfig::default().vmo(inspect_vmo));
        let _a = inspector.root().create_child("a");
        assert_data_tree!(returned_inspector, root: {
            a: {},
        });
    }

    struct StartTestHarness {
        pub mlme_init_receiver: Pin<Box<oneshot::Receiver<()>>>,
        // TODO(https://fxbug.dev/335283785): Remove or explain unused code.
        #[allow(dead_code)]
        pub driver_event_sink: DriverEventSink,
    }

    impl StartTestHarness {
        fn new(
            fake_device: FakeDevice,
        ) -> (
            impl Future<
                Output = Result<
                    StartedDriver<
                        Pin<Box<dyn Future<Output = Result<(), Error>>>>,
                        Pin<Box<impl Future<Output = Result<(), Error>>>>,
                    >,
                    zx::Status,
                >,
            >,
            Self,
        ) {
            let (mlme_init_sender, mlme_init_receiver) = oneshot::channel();
            let (driver_event_sink, driver_event_stream) = DriverEventSink::new();

            (
                Box::pin(start(
                    mlme_init_sender,
                    driver_event_sink.clone(),
                    driver_event_stream,
                    fake_device,
                )),
                Self { mlme_init_receiver: Box::pin(mlme_init_receiver), driver_event_sink },
            )
        }
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn start_fails_on_bad_bootstrap() {
        let (fake_device, _fake_device_state) = FakeDevice::new_with_config(
            FakeDeviceConfig::default().with_mock_start_result(Err(zx::Status::INTERRUPTED_RETRY)),
        )
        .await;
        let (mut start_fut, _harness) = StartTestHarness::new(fake_device);

        assert!(matches!(
            TestExecutor::poll_until_stalled(&mut start_fut).await,
            Poll::Ready(Err(zx::Status::INTERRUPTED_RETRY))
        ));
    }

    fn bootstrap_generic_sme_proxy_and_inspect_vmo(
        usme_bootstrap_client_end: fidl::endpoints::ClientEnd<fidl_sme::UsmeBootstrapMarker>,
    ) -> (fidl_sme::GenericSmeProxy, impl Future<Output = Result<Vmo, fidl::Error>>) {
        let usme_client_proxy = usme_bootstrap_client_end.into_proxy();

        let legacy_privacy_support =
            fidl_sme::LegacyPrivacySupport { wep_supported: false, wpa1_supported: false };
        let (generic_sme_proxy, generic_sme_server) =
            fidl::endpoints::create_proxy::<fidl_sme::GenericSmeMarker>();
        (generic_sme_proxy, usme_client_proxy.start(generic_sme_server, &legacy_privacy_support))
    }

    #[test_case(FakeDeviceConfig::default().with_mock_query_response(Err(zx::Status::IO_DATA_INTEGRITY)), zx::Status::IO_DATA_INTEGRITY)]
    #[test_case(FakeDeviceConfig::default().with_mock_mac_sublayer_support(Err(zx::Status::IO_DATA_INTEGRITY)), zx::Status::IO_DATA_INTEGRITY)]
    #[test_case(FakeDeviceConfig::default().with_mock_mac_implementation_type(fidl_common::MacImplementationType::Fullmac), zx::Status::INTERNAL)]
    #[test_case(FakeDeviceConfig::default().with_mock_security_support(Err(zx::Status::IO_DATA_INTEGRITY)), zx::Status::IO_DATA_INTEGRITY)]
    #[test_case(FakeDeviceConfig::default().with_mock_spectrum_management_support(Err(zx::Status::IO_DATA_INTEGRITY)), zx::Status::IO_DATA_INTEGRITY)]
    #[test_case(FakeDeviceConfig::default().with_mock_mac_role(fidl_common::WlanMacRole::__SourceBreaking { unknown_ordinal: 0 }), zx::Status::INTERNAL)]
    #[fuchsia::test(allow_stalls = false)]
    async fn start_fails_on_query_error(
        fake_device_config: FakeDeviceConfig,
        expected_status: zx::Status,
    ) {
        let (fake_device, fake_device_state) =
            FakeDevice::new_with_config(fake_device_config).await;
        let (mut start_fut, _harness) = StartTestHarness::new(fake_device);

        let usme_bootstrap_client_end =
            fake_device_state.lock().usme_bootstrap_client_end.take().unwrap();
        let (_generic_sme_proxy, _inspect_vmo_fut) =
            bootstrap_generic_sme_proxy_and_inspect_vmo(usme_bootstrap_client_end);

        match TestExecutor::poll_until_stalled(&mut start_fut).await {
            Poll::Ready(Err(status)) => assert_eq!(status, expected_status),
            Poll::Pending => panic!("start_fut still pending!"),
            Poll::Ready(Ok(_)) => panic!("start_fut completed with Ok value"),
        }
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn start_fail_on_dropped_mlme_event_stream() {
        let (fake_device, fake_device_state) = FakeDevice::new().await;
        let (mut start_fut, _harness) = StartTestHarness::new(fake_device);

        let usme_bootstrap_client_end =
            fake_device_state.lock().usme_bootstrap_client_end.take().unwrap();
        let (_generic_sme_proxy, _inspect_vmo_fut) =
            bootstrap_generic_sme_proxy_and_inspect_vmo(usme_bootstrap_client_end);

        let _ = fake_device_state.lock().mlme_event_stream.take();
        match TestExecutor::poll_until_stalled(&mut start_fut).await {
            Poll::Ready(Err(status)) => assert_eq!(status, zx::Status::INTERNAL),
            Poll::Pending => panic!("start_fut still pending!"),
            Poll::Ready(Ok(_)) => panic!("start_fut completed with Ok value"),
        }
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn start_succeeds() {
        let (fake_device, fake_device_state) = FakeDevice::new_with_config(
            FakeDeviceConfig::default()
                .with_mock_sta_addr([2u8; 6])
                .with_mock_mac_role(fidl_common::WlanMacRole::Client),
        )
        .await;
        let (mut start_fut, mut harness) = StartTestHarness::new(fake_device);

        let usme_bootstrap_client_end =
            fake_device_state.lock().usme_bootstrap_client_end.take().unwrap();
        let (generic_sme_proxy, _inspect_vmo_fut) =
            bootstrap_generic_sme_proxy_and_inspect_vmo(usme_bootstrap_client_end);

        let StartedDriver {
            softmac_ifc_bridge_request_stream: _softmac_ifc_bridge_request_stream,
            mut mlme,
            sme,
        } = match TestExecutor::poll_until_stalled(&mut start_fut).await {
            Poll::Ready(Ok(x)) => x,
            Poll::Ready(Err(status)) => {
                panic!("start_fut unexpectedly failed; {}", status)
            }
            Poll::Pending => panic!("start_fut still pending!"),
        };

        assert_variant!(TestExecutor::poll_until_stalled(&mut mlme).await, Poll::Pending);
        assert!(matches!(
            TestExecutor::poll_until_stalled(&mut harness.mlme_init_receiver).await,
            Poll::Ready(Ok(()))
        ));

        let resp_fut = generic_sme_proxy.query();
        let mut resp_fut = pin!(resp_fut);
        assert_variant!(TestExecutor::poll_until_stalled(&mut resp_fut).await, Poll::Pending);

        let sme_and_mlme = [sme, mlme].into_iter().collect::<FuturesUnordered<_>>();
        let mut sme_and_mlme = pin!(sme_and_mlme);
        assert!(matches!(
            TestExecutor::poll_until_stalled(&mut sme_and_mlme.next()).await,
            Poll::Pending
        ));

        assert!(matches!(
            TestExecutor::poll_until_stalled(&mut resp_fut).await,
            Poll::Ready(Ok(fidl_sme::GenericSmeQuery {
                role: fidl_common::WlanMacRole::Client,
                sta_addr: [2, 2, 2, 2, 2, 2],
            }))
        ));
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn serve_wlansoftmac_ifc_bridge_fails_on_request_stream_error() {
        let (driver_event_sink, _driver_event_stream) = DriverEventSink::new();
        let (softmac_ifc_bridge_client, softmac_ifc_bridge_server) =
            fidl::endpoints::create_endpoints::<fidl_softmac::WlanSoftmacIfcBridgeMarker>();
        let softmac_ifc_bridge_request_stream = softmac_ifc_bridge_server.into_stream();
        let softmac_ifc_bridge_channel = softmac_ifc_bridge_client.into_channel();

        let server_fut =
            serve_wlan_softmac_ifc_bridge(driver_event_sink, softmac_ifc_bridge_request_stream);
        let mut server_fut = pin!(server_fut);
        assert_variant!(TestExecutor::poll_until_stalled(&mut server_fut).await, Poll::Pending);

        softmac_ifc_bridge_channel.write(&[], &mut []).unwrap();
        assert_variant!(
            TestExecutor::poll_until_stalled(&mut server_fut).await,
            Poll::Ready(Err(_))
        );
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn serve_wlansoftmac_ifc_bridge_exits_on_request_stream_end() {
        let (driver_event_sink, _driver_event_stream) = DriverEventSink::new();
        let (softmac_ifc_bridge_client, softmac_ifc_bridge_server) =
            fidl::endpoints::create_endpoints::<fidl_softmac::WlanSoftmacIfcBridgeMarker>();
        let softmac_ifc_bridge_request_stream = softmac_ifc_bridge_server.into_stream();

        let server_fut =
            serve_wlan_softmac_ifc_bridge(driver_event_sink, softmac_ifc_bridge_request_stream);
        let mut server_fut = pin!(server_fut);
        assert_variant!(TestExecutor::poll_until_stalled(&mut server_fut).await, Poll::Pending);

        drop(softmac_ifc_bridge_client);
        assert_variant!(
            TestExecutor::poll_until_stalled(&mut server_fut).await,
            Poll::Ready(Err(_))
        );
    }

    #[test_case(fidl_softmac::WlanSoftmacIfcBaseNotifyScanCompleteRequest {
                status: None,
                scan_id: Some(754),
                ..Default::default()
    })]
    #[test_case(fidl_softmac::WlanSoftmacIfcBaseNotifyScanCompleteRequest {
                status: Some(zx::Status::OK.into_raw()),
                scan_id: None,
                ..Default::default()
            })]
    #[fuchsia::test(allow_stalls = false)]
    async fn serve_wlansoftmac_ifc_bridge_exits_on_invalid_notify_scan_complete_request(
        request: fidl_softmac::WlanSoftmacIfcBaseNotifyScanCompleteRequest,
    ) {
        let (driver_event_sink, mut driver_event_stream) = DriverEventSink::new();
        let (softmac_ifc_bridge_proxy, softmac_ifc_bridge_server) =
            fidl::endpoints::create_proxy::<fidl_softmac::WlanSoftmacIfcBridgeMarker>();
        let softmac_ifc_bridge_request_stream = softmac_ifc_bridge_server.into_stream();

        let server_fut =
            serve_wlan_softmac_ifc_bridge(driver_event_sink, softmac_ifc_bridge_request_stream);
        let mut server_fut = pin!(server_fut);

        let resp_fut = softmac_ifc_bridge_proxy.notify_scan_complete(&request);
        let mut resp_fut = pin!(resp_fut);
        assert_variant!(TestExecutor::poll_until_stalled(&mut resp_fut).await, Poll::Pending);
        assert_variant!(
            TestExecutor::poll_until_stalled(&mut server_fut).await,
            Poll::Ready(Err(_))
        );
        assert_variant!(TestExecutor::poll_until_stalled(&mut resp_fut).await, Poll::Ready(Ok(())));
        assert!(matches!(driver_event_stream.try_next(), Ok(None)));
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn serve_wlansoftmac_ifc_bridge_enqueues_notify_scan_complete() {
        let (driver_event_sink, mut driver_event_stream) = DriverEventSink::new();
        let (softmac_ifc_bridge_proxy, softmac_ifc_bridge_server) =
            fidl::endpoints::create_proxy::<fidl_softmac::WlanSoftmacIfcBridgeMarker>();
        let softmac_ifc_bridge_request_stream = softmac_ifc_bridge_server.into_stream();

        let server_fut =
            serve_wlan_softmac_ifc_bridge(driver_event_sink, softmac_ifc_bridge_request_stream);
        let mut server_fut = pin!(server_fut);

        let resp_fut = softmac_ifc_bridge_proxy.notify_scan_complete(
            &fidl_softmac::WlanSoftmacIfcBaseNotifyScanCompleteRequest {
                status: Some(zx::Status::OK.into_raw()),
                scan_id: Some(754),
                ..Default::default()
            },
        );
        let mut resp_fut = pin!(resp_fut);
        assert_variant!(TestExecutor::poll_until_stalled(&mut resp_fut).await, Poll::Pending);
        assert_variant!(TestExecutor::poll_until_stalled(&mut server_fut).await, Poll::Pending);
        assert_variant!(TestExecutor::poll_until_stalled(&mut resp_fut).await, Poll::Ready(Ok(())));

        assert!(matches!(
            driver_event_stream.try_next(),
            Ok(Some(DriverEvent::ScanComplete { status: zx::Status::OK, scan_id: 754 }))
        ));
    }

    struct ServeTestHarness {
        pub mlme_init_sender: oneshot::Sender<()>,
        pub driver_event_stream: mpsc::UnboundedReceiver<DriverEvent>,
        pub softmac_ifc_bridge_proxy: fidl_softmac::WlanSoftmacIfcBridgeProxy,
        pub complete_mlme_sender: oneshot::Sender<Result<(), anyhow::Error>>,
        pub complete_sme_sender: oneshot::Sender<Result<(), anyhow::Error>>,
    }

    impl ServeTestHarness {
        fn new() -> (Pin<Box<impl Future<Output = Result<(), zx::Status>>>>, ServeTestHarness) {
            let (mlme_init_sender, mlme_init_receiver) = oneshot::channel();
            let (driver_event_sink, driver_event_stream) = DriverEventSink::new();
            let (softmac_ifc_bridge_proxy, softmac_ifc_bridge_server) =
                fidl::endpoints::create_proxy::<fidl_softmac::WlanSoftmacIfcBridgeMarker>();
            let softmac_ifc_bridge_request_stream = softmac_ifc_bridge_server.into_stream();
            let (complete_mlme_sender, complete_mlme_receiver) = oneshot::channel();
            let mlme = Box::pin(async { complete_mlme_receiver.await.unwrap() });
            let (complete_sme_sender, complete_sme_receiver) = oneshot::channel();
            let sme = Box::pin(async { complete_sme_receiver.await.unwrap() });

            (
                Box::pin(serve(
                    mlme_init_receiver,
                    driver_event_sink,
                    softmac_ifc_bridge_request_stream,
                    mlme,
                    sme,
                )),
                ServeTestHarness {
                    mlme_init_sender,
                    driver_event_stream,
                    softmac_ifc_bridge_proxy,
                    complete_mlme_sender,
                    complete_sme_sender,
                },
            )
        }
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn serve_wlansoftmac_ifc_bridge_enqueues_report_tx_result() {
        let (driver_event_sink, mut driver_event_stream) = DriverEventSink::new();
        let (softmac_ifc_bridge_proxy, softmac_ifc_bridge_server) =
            fidl::endpoints::create_proxy::<fidl_softmac::WlanSoftmacIfcBridgeMarker>();
        let softmac_ifc_bridge_request_stream = softmac_ifc_bridge_server.into_stream();

        let server_fut =
            serve_wlan_softmac_ifc_bridge(driver_event_sink, softmac_ifc_bridge_request_stream);
        let mut server_fut = pin!(server_fut);

        let resp_fut = softmac_ifc_bridge_proxy.report_tx_result(&fidl_common::WlanTxResult {
            tx_result_entry: [fidl_common::WlanTxResultEntry {
                tx_vector_idx: fidl_common::WLAN_TX_VECTOR_IDX_INVALID,
                attempts: 0,
            }; fidl_common::WLAN_TX_RESULT_MAX_ENTRY as usize],
            peer_addr: [3; 6],
            result_code: fidl_common::WlanTxResultCode::Failed,
        });
        let mut resp_fut = pin!(resp_fut);
        assert_variant!(TestExecutor::poll_until_stalled(&mut resp_fut).await, Poll::Pending);
        assert_variant!(TestExecutor::poll_until_stalled(&mut server_fut).await, Poll::Pending);
        assert_variant!(TestExecutor::poll_until_stalled(&mut resp_fut).await, Poll::Ready(Ok(())));

        match driver_event_stream.try_next().unwrap().unwrap() {
            DriverEvent::TxResultReport { tx_result } => {
                assert_eq!(
                    tx_result,
                    fidl_common::WlanTxResult {
                        tx_result_entry: [fidl_common::WlanTxResultEntry {
                            tx_vector_idx: fidl_common::WLAN_TX_VECTOR_IDX_INVALID,
                            attempts: 0
                        };
                            fidl_common::WLAN_TX_RESULT_MAX_ENTRY as usize],
                        peer_addr: [3; 6],
                        result_code: fidl_common::WlanTxResultCode::Failed,
                    }
                );
            }
            _ => panic!("Unexpected DriverEvent!"),
        }
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn serve_exits_with_error_if_mlme_init_sender_dropped() {
        let (mut serve_fut, harness) = ServeTestHarness::new();

        assert_variant!(TestExecutor::poll_until_stalled(&mut serve_fut).await, Poll::Pending);
        drop(harness.mlme_init_sender);
        assert_variant!(
            TestExecutor::poll_until_stalled(&mut serve_fut).await,
            Poll::Ready(Err(zx::Status::INTERNAL))
        );
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn serve_exits_successfully_if_mlme_completes_just_before_init_sender_dropped() {
        let (mut serve_fut, harness) = ServeTestHarness::new();

        harness.complete_mlme_sender.send(Ok(())).unwrap();
        drop(harness.mlme_init_sender);
        assert_variant!(
            TestExecutor::poll_until_stalled(&mut serve_fut).await,
            Poll::Ready(Err(zx::Status::INTERNAL))
        );
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn serve_exits_successfully_if_mlme_completes_just_before_init() {
        let (mut serve_fut, harness) = ServeTestHarness::new();

        harness.complete_mlme_sender.send(Ok(())).unwrap();
        harness.mlme_init_sender.send(()).unwrap();
        assert_variant!(
            TestExecutor::poll_until_stalled(&mut serve_fut).await,
            Poll::Ready(Ok(()))
        );
    }

    #[test_case(Ok(()))]
    #[test_case(Err(format_err!("")))]
    #[fuchsia::test(allow_stalls = false)]
    async fn serve_exits_with_error_if_mlme_completes_before_init(
        early_mlme_result: Result<(), Error>,
    ) {
        let (mut serve_fut, harness) = ServeTestHarness::new();

        assert_variant!(TestExecutor::poll_until_stalled(&mut serve_fut).await, Poll::Pending);
        harness.complete_mlme_sender.send(early_mlme_result).unwrap();
        assert_variant!(
            TestExecutor::poll_until_stalled(&mut serve_fut).await,
            Poll::Ready(Err(zx::Status::INTERNAL))
        );
    }

    #[test_case(Ok(()))]
    #[test_case(Err(format_err!("")))]
    #[fuchsia::test(allow_stalls = false)]
    async fn serve_exits_with_error_if_sme_shuts_down_before_mlme(
        early_sme_result: Result<(), Error>,
    ) {
        let (mut serve_fut, harness) = ServeTestHarness::new();

        assert_variant!(TestExecutor::poll_until_stalled(&mut serve_fut).await, Poll::Pending);
        harness.mlme_init_sender.send(()).unwrap();
        assert_variant!(TestExecutor::poll_until_stalled(&mut serve_fut).await, Poll::Pending);
        harness.complete_sme_sender.send(early_sme_result).unwrap();
        assert_variant!(
            TestExecutor::poll_until_stalled(&mut serve_fut).await,
            Poll::Ready(Err(zx::Status::INTERNAL))
        );
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn serve_exits_with_error_if_mlme_completes_with_error() {
        let (mut serve_fut, harness) = ServeTestHarness::new();

        assert_variant!(TestExecutor::poll_until_stalled(&mut serve_fut).await, Poll::Pending);
        harness.mlme_init_sender.send(()).unwrap();
        assert_variant!(TestExecutor::poll_until_stalled(&mut serve_fut).await, Poll::Pending);
        harness.complete_mlme_sender.send(Err(format_err!("mlme error"))).unwrap();
        assert_eq!(
            TestExecutor::poll_until_stalled(&mut serve_fut).await,
            Poll::Ready(Err(zx::Status::INTERNAL))
        );
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn serve_exits_with_error_if_sme_shuts_down_with_error() {
        let (mut serve_fut, harness) = ServeTestHarness::new();

        assert_variant!(TestExecutor::poll_until_stalled(&mut serve_fut).await, Poll::Pending);
        harness.mlme_init_sender.send(()).unwrap();
        assert_variant!(TestExecutor::poll_until_stalled(&mut serve_fut).await, Poll::Pending);
        harness.complete_mlme_sender.send(Ok(())).unwrap();
        harness.complete_sme_sender.send(Err(format_err!("sme error"))).unwrap();
        assert_eq!(
            TestExecutor::poll_until_stalled(&mut serve_fut).await,
            Poll::Ready(Err(zx::Status::INTERNAL))
        );
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn serve_exits_with_error_if_bridge_exits_early_with_error() {
        let (mut serve_fut, harness) = ServeTestHarness::new();

        assert_variant!(TestExecutor::poll_until_stalled(&mut serve_fut).await, Poll::Pending);
        harness.mlme_init_sender.send(()).unwrap();
        assert_variant!(TestExecutor::poll_until_stalled(&mut serve_fut).await, Poll::Pending);

        // Cause the bridge to encounter an error when the client drops its endpoint.
        drop(harness.softmac_ifc_bridge_proxy);
        assert_eq!(serve_fut.await, Err(zx::Status::INTERNAL));
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn serve_exits_with_error_if_bridge_cannot_queue_stop() {
        let (mut serve_fut, harness) = ServeTestHarness::new();

        assert_variant!(TestExecutor::poll_until_stalled(&mut serve_fut).await, Poll::Pending);
        harness.mlme_init_sender.send(()).unwrap();
        assert_variant!(TestExecutor::poll_until_stalled(&mut serve_fut).await, Poll::Pending);

        // Cause the bridge to encounter an error when the bridge cannot queue the DriverEvent::Stop.
        drop(harness.driver_event_stream);
        harness.softmac_ifc_bridge_proxy.stop_bridged_driver().await.unwrap();
        assert_eq!(serve_fut.await, Err(zx::Status::INTERNAL));
    }

    #[test_case(true)]
    #[test_case(false)]
    #[fuchsia::test(allow_stalls = false)]
    async fn serve_shuts_down_gracefully(bridge_shutdown_before_mlme: bool) {
        let (mut serve_fut, mut harness) = ServeTestHarness::new();

        assert_variant!(TestExecutor::poll_until_stalled(&mut serve_fut).await, Poll::Pending);
        harness.mlme_init_sender.send(()).unwrap();
        assert_variant!(TestExecutor::poll_until_stalled(&mut serve_fut).await, Poll::Pending);
        let mut stop_response_fut = harness.softmac_ifc_bridge_proxy.stop_bridged_driver();

        // The server should not fail if the MLME future completes before or after the bridge futures
        // completes. This is because the bridge server sends the message for MLME to shutdown just
        // before completing. And so it's possible for MLME to shutdown before the bridge server completes.
        //
        // Note that both orderings are possible even with a single threaded executor. This is because
        // the bridge futures actually sends two messages before completing. The first to MLME to shutdown
        // and the second to the bridge exit receiver with the result from the bridge completing. Thus,
        // there is a race between the MLME and bridge exit receiver, either of which could run first
        // depending on the executor.
        if bridge_shutdown_before_mlme {
            assert_variant!(
                TestExecutor::poll_until_stalled(&mut stop_response_fut).await,
                Poll::Pending,
            );
            let responder = assert_variant!(harness.driver_event_stream.next().await,
                Some(DriverEvent::Stop{ responder }) => responder);
            responder.send().unwrap();
            assert_variant!(
                TestExecutor::poll_until_stalled(&mut stop_response_fut).await,
                Poll::Ready(Ok(()))
            );

            harness.complete_mlme_sender.send(Ok(())).unwrap();
        } else {
            harness.complete_mlme_sender.send(Ok(())).unwrap();
            assert_eq!(TestExecutor::poll_until_stalled(&mut serve_fut).await, Poll::Pending);

            assert_variant!(
                TestExecutor::poll_until_stalled(&mut stop_response_fut).await,
                Poll::Pending,
            );
            let responder = assert_variant!(harness.driver_event_stream.next().await,
                Some(DriverEvent::Stop{ responder }) => responder);
            responder.send().unwrap();
            assert_variant!(
                TestExecutor::poll_until_stalled(&mut stop_response_fut).await,
                Poll::Ready(Ok(()))
            );
        }

        assert_eq!(TestExecutor::poll_until_stalled(&mut serve_fut).await, Poll::Pending);
        harness.complete_sme_sender.send(Ok(())).unwrap();
        assert_eq!(TestExecutor::poll_until_stalled(&mut serve_fut).await, Poll::Ready(Ok(())));
    }

    #[derive(Debug)]
    struct StartAndServeTestHarness<F> {
        pub start_and_serve_fut: F,
        pub start_complete_receiver: oneshot::Receiver<zx::sys::zx_status_t>,
        pub generic_sme_proxy: fidl_sme::GenericSmeProxy,
    }

    /// This function wraps start_and_serve() with a FakeDevice provided by a test.
    ///
    /// The returned start_and_serve() future will run the WlanSoftmacIfcBridge, MLME, and SME servers when
    /// run on an executor.
    ///
    /// An Err value will be returned if start_and_serve() encounters an error completing the bootstrap
    /// of the SME server.
    async fn start_and_serve_with_device(
        fake_device: FakeDevice,
    ) -> Result<StartAndServeTestHarness<impl Future<Output = Result<(), zx::Status>>>, zx::Status>
    {
        let (start_complete_sender, mut start_complete_receiver) =
            oneshot::channel::<zx::sys::zx_status_t>();
        let start_and_serve_fut = start_and_serve(
            Completer::new(move |status| {
                start_complete_sender.send(status).expect("Failed to signal start complete.")
            }),
            fake_device.clone(),
        );
        let mut start_and_serve_fut = Box::pin(start_and_serve_fut);

        let usme_bootstrap_client_end = fake_device.state().lock().usme_bootstrap_client_end.take();
        match usme_bootstrap_client_end {
            // Simulate an errant initialization case where the UsmeBootstrap client end has been dropped
            // during initialization.
            None => match TestExecutor::poll_until_stalled(&mut start_and_serve_fut).await {
                Poll::Pending => panic!(
                    "start_and_serve() failed to exit when the UsmeBootstrap client was dropped."
                ),
                Poll::Ready(result) => {
                    assert_variant!(
                        TestExecutor::poll_until_stalled(&mut start_complete_receiver).await,
                        Poll::Ready(Ok(status)) => assert_ne!(status, zx::Status::OK.into_raw())
                    );
                    return Err(result.unwrap_err());
                }
            },
            // Simulate the normal initialization case where the the UsmeBootstrap client end is active
            // during initialization.
            Some(usme_bootstrap_client_end) => {
                let (generic_sme_proxy, inspect_vmo_fut) =
                    bootstrap_generic_sme_proxy_and_inspect_vmo(usme_bootstrap_client_end);
                let start_and_serve_fut = match TestExecutor::poll_until_stalled(
                    &mut start_and_serve_fut,
                )
                .await
                {
                    Poll::Pending => start_and_serve_fut,
                    Poll::Ready(result) => {
                        assert_variant!(
                            TestExecutor::poll_until_stalled(&mut start_complete_receiver)
                                .await,
                            Poll::Ready(Ok(status)) => assert_ne!(status, zx::Status::OK.into_raw())
                        );
                        return Err(result.unwrap_err());
                    }
                };

                inspect_vmo_fut.await.expect("Failed to bootstrap USME.");

                Ok(StartAndServeTestHarness {
                    start_and_serve_fut,
                    start_complete_receiver,
                    generic_sme_proxy,
                })
            }
        }
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn start_and_serve_fails_on_dropped_usme_bootstrap_client() {
        let (fake_device, fake_device_state) = FakeDevice::new().await;
        fake_device_state.lock().usme_bootstrap_client_end = None;
        match start_and_serve_with_device(fake_device.clone()).await {
            Ok(_) => panic!(
                "start_and_serve() does not fail when the UsmeBootstrap client end is dropped."
            ),
            Err(status) => assert_eq!(status, zx::Status::BAD_STATE),
        }
    }

    // Exhaustive feature tests are unit tested on start()
    #[fuchsia::test(allow_stalls = false)]
    async fn start_and_serve_fails_with_wrong_mac_implementation_type() {
        let (fake_device, _fake_device_state) = FakeDevice::new_with_config(
            FakeDeviceConfig::default()
                .with_mock_mac_implementation_type(fidl_common::MacImplementationType::Fullmac),
        )
        .await;

        match start_and_serve_with_device(fake_device).await {
            Ok(_) => panic!(
                "start_and_serve() future did not terminate before attempting bootstrap SME."
            ),
            Err(status) => assert_eq!(status, zx::Status::INTERNAL),
        };
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn start_and_serve_fails_on_dropped_mlme_event_stream() {
        let (mut fake_device, _fake_device_state) = FakeDevice::new().await;
        let _ = fake_device.take_mlme_event_stream();
        match start_and_serve_with_device(fake_device.clone()).await {
            Ok(_) => {
                panic!("start_and_serve() does not fail when the MLME event stream is missing.")
            }
            Err(status) => assert_eq!(status, zx::Status::INTERNAL),
        }
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn start_and_serve_fails_on_dropped_generic_sme_client() {
        let (fake_device, _fake_device_state) = FakeDevice::new().await;
        let StartAndServeTestHarness {
            mut start_and_serve_fut,
            mut start_complete_receiver,
            generic_sme_proxy,
        } = start_and_serve_with_device(fake_device)
            .await
            .expect("Failed to initiate wlansoftmac setup.");
        assert_variant!(
            TestExecutor::poll_until_stalled(&mut start_complete_receiver).await,
            Poll::Ready(Ok(status)) => assert_eq!(zx::Status::OK.into_raw(), status)
        );
        assert_eq!(TestExecutor::poll_until_stalled(&mut start_and_serve_fut).await, Poll::Pending);

        drop(generic_sme_proxy);

        assert_eq!(
            TestExecutor::poll_until_stalled(&mut start_and_serve_fut).await,
            Poll::Ready(Err(zx::Status::INTERNAL))
        );
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn start_and_serve_shuts_down_gracefully() {
        let (fake_device, fake_device_state) = FakeDevice::new().await;
        let StartAndServeTestHarness {
            mut start_and_serve_fut,
            mut start_complete_receiver,
            generic_sme_proxy: _generic_sme_proxy,
        } = start_and_serve_with_device(fake_device)
            .await
            .expect("Failed to initiate wlansoftmac setup.");
        assert_eq!(TestExecutor::poll_until_stalled(&mut start_and_serve_fut).await, Poll::Pending);
        assert_variant!(
            TestExecutor::poll_until_stalled(&mut start_complete_receiver).await,
            Poll::Ready(Ok(status)) => assert_eq!(zx::Status::OK.into_raw(), status)
        );

        let wlan_softmac_ifc_bridge_proxy =
            fake_device_state.lock().wlan_softmac_ifc_bridge_proxy.take().unwrap();
        let stop_response_fut = wlan_softmac_ifc_bridge_proxy.stop_bridged_driver();
        assert_variant!(futures::join!(start_and_serve_fut, stop_response_fut), (Ok(()), Ok(())));
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn start_and_serve_responds_to_generic_sme_requests() {
        let (fake_device, fake_device_state) = FakeDevice::new().await;
        let StartAndServeTestHarness {
            mut start_and_serve_fut,
            mut start_complete_receiver,
            generic_sme_proxy,
        } = start_and_serve_with_device(fake_device)
            .await
            .expect("Failed to initiate wlansoftmac setup.");
        assert_variant!(
            TestExecutor::poll_until_stalled(&mut start_complete_receiver).await,
            Poll::Ready(Ok(status)) => assert_eq!(zx::Status::OK.into_raw(), status)
        );

        let (sme_telemetry_proxy, sme_telemetry_server) = fidl::endpoints::create_proxy();
        let (client_sme_proxy, client_sme_server) = fidl::endpoints::create_proxy();

        let resp_fut = generic_sme_proxy.get_sme_telemetry(sme_telemetry_server);
        let mut resp_fut = pin!(resp_fut);

        // First poll `get_sme_telemetry` to send a `GetSmeTelemetry` request to the SME server, and then
        // poll the SME server process it. Finally, expect `get_sme_telemetry` to complete with `Ok(())`.
        assert_variant!(TestExecutor::poll_until_stalled(&mut resp_fut).await, Poll::Pending);
        assert_eq!(TestExecutor::poll_until_stalled(&mut start_and_serve_fut).await, Poll::Pending);
        assert_variant!(
            TestExecutor::poll_until_stalled(&mut resp_fut).await,
            Poll::Ready(Ok(Ok(())))
        );

        let resp_fut = generic_sme_proxy.get_client_sme(client_sme_server);
        let mut resp_fut = pin!(resp_fut);

        // First poll `get_client_sme` to send a `GetClientSme` request to the SME server, and then poll the
        // SME server process it. Finally, expect `get_client_sme` to complete with `Ok(())`.
        assert_variant!(TestExecutor::poll_until_stalled(&mut resp_fut).await, Poll::Pending);
        assert_eq!(TestExecutor::poll_until_stalled(&mut start_and_serve_fut).await, Poll::Pending);
        resp_fut.await.expect("Generic SME proxy failed").expect("Client SME request failed");

        let wlan_softmac_ifc_bridge_proxy =
            fake_device_state.lock().wlan_softmac_ifc_bridge_proxy.take().unwrap();
        let stop_response_fut = wlan_softmac_ifc_bridge_proxy.stop_bridged_driver();
        assert_variant!(futures::join!(start_and_serve_fut, stop_response_fut), (Ok(()), Ok(())));

        // All SME proxies should shutdown.
        assert!(generic_sme_proxy.is_closed());
        assert!(sme_telemetry_proxy.is_closed());
        assert!(client_sme_proxy.is_closed());
    }

    // Mocking a passive scan verifies the path through SME, MLME, and the FFI is functional. Other paths
    // are much more complex to mock and sufficiently covered by other testing. For example, queueing an
    // Ethernet frame requires mocking an association first, and the outcome of a reported Tx result cannot
    // be confirmed because the Minstrel is internal to MLME.
    #[fuchsia::test(allow_stalls = false)]
    async fn start_and_serve_responds_to_passive_scan_request() {
        let (fake_device, fake_device_state) = FakeDevice::new().await;
        let StartAndServeTestHarness {
            mut start_and_serve_fut,
            mut start_complete_receiver,
            generic_sme_proxy,
        } = start_and_serve_with_device(fake_device)
            .await
            .expect("Failed to initiate wlansoftmac setup.");
        assert_variant!(
            TestExecutor::poll_until_stalled(&mut start_complete_receiver).await,
            Poll::Ready(Ok(status)) => assert_eq!(zx::Status::OK.into_raw(), status)
        );

        let (client_sme_proxy, client_sme_server) = fidl::endpoints::create_proxy();

        let resp_fut = generic_sme_proxy.get_client_sme(client_sme_server);
        let mut resp_fut = pin!(resp_fut);
        assert_variant!(TestExecutor::poll_until_stalled(&mut resp_fut).await, Poll::Pending);
        assert_eq!(TestExecutor::poll_until_stalled(&mut start_and_serve_fut).await, Poll::Pending);
        assert!(matches!(
            TestExecutor::poll_until_stalled(&mut resp_fut).await,
            Poll::Ready(Ok(Ok(())))
        ));

        let scan_response_fut =
            client_sme_proxy.scan(&fidl_sme::ScanRequest::Passive(fidl_sme::PassiveScanRequest {}));
        let mut scan_response_fut = pin!(scan_response_fut);
        assert!(matches!(
            TestExecutor::poll_until_stalled(&mut scan_response_fut).await,
            Poll::Pending
        ));

        assert!(fake_device_state.lock().captured_passive_scan_request.is_none());
        assert_eq!(TestExecutor::poll_until_stalled(&mut start_and_serve_fut).await, Poll::Pending);
        assert!(fake_device_state.lock().captured_passive_scan_request.is_some());

        let wlan_softmac_ifc_bridge_proxy =
            fake_device_state.lock().wlan_softmac_ifc_bridge_proxy.take().unwrap();
        let notify_scan_complete_fut = wlan_softmac_ifc_bridge_proxy.notify_scan_complete(
            &fidl_softmac::WlanSoftmacIfcBaseNotifyScanCompleteRequest {
                status: Some(zx::Status::OK.into_raw()),
                scan_id: Some(0),
                ..Default::default()
            },
        );
        notify_scan_complete_fut.await.expect("Failed to receive NotifyScanComplete response");
        assert_eq!(TestExecutor::poll_until_stalled(&mut start_and_serve_fut).await, Poll::Pending);
        assert!(matches!(
            TestExecutor::poll_until_stalled(&mut scan_response_fut).await,
            Poll::Ready(Ok(_))
        ));

        let stop_response_fut = wlan_softmac_ifc_bridge_proxy.stop_bridged_driver();
        assert_variant!(futures::join!(start_and_serve_fut, stop_response_fut), (Ok(()), Ok(())));

        // All SME proxies should shutdown.
        assert!(generic_sme_proxy.is_closed());
        assert!(client_sme_proxy.is_closed());
    }
}