vhost 0.16.0

a pure rust library for vdpa, vhost and vhost-user
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
// Copyright (C) 2019 Alibaba Cloud Computing. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Traits and Struct for vhost-user frontend.

use std::fs::File;
use std::mem;
use std::os::fd::OwnedFd;
use std::os::unix::io::{AsRawFd, RawFd};
use std::os::unix::net::UnixStream;
use std::path::Path;
use std::sync::{Arc, Mutex, MutexGuard};

use vm_memory::ByteValued;
use vmm_sys_util::eventfd::EventFd;

use super::connection::Endpoint;
use super::message::*;
use super::{take_single_file, Error as VhostUserError, Result as VhostUserResult};
use crate::backend::{
    VhostBackend, VhostUserDirtyLogRegion, VhostUserMemoryRegionInfo, VringConfigData,
};
use crate::{Error, Result};

/// Trait for vhost-user frontend to provide extra methods not covered by the VhostBackend yet.
pub trait VhostUserFrontend: VhostBackend {
    /// Get the protocol feature bitmask from the underlying vhost implementation.
    fn get_protocol_features(&mut self) -> Result<VhostUserProtocolFeatures>;

    /// Enable protocol features in the underlying vhost implementation.
    fn set_protocol_features(&mut self, features: VhostUserProtocolFeatures) -> Result<()>;

    /// Query how many queues the backend supports.
    fn get_queue_num(&mut self) -> Result<u64>;

    /// Disable all rings and reset the internal device state.
    fn reset_device(&mut self) -> Result<()>;

    /// Signal backend to enable or disable corresponding vring.
    ///
    /// Backend must not pass data to/from the backend until ring is enabled by
    /// VHOST_USER_SET_VRING_ENABLE with parameter 1, or after it has been
    /// disabled by VHOST_USER_SET_VRING_ENABLE with parameter 0.
    fn set_vring_enable(&mut self, queue_index: usize, enable: bool) -> Result<()>;

    /// Fetch the contents of the virtio device configuration space.
    fn get_config(
        &mut self,
        offset: u32,
        size: u32,
        flags: VhostUserConfigFlags,
        buf: &[u8],
    ) -> Result<(VhostUserConfig, VhostUserConfigPayload)>;

    /// Change the virtio device configuration space. It also can be used for live migration on the
    /// destination host to set readonly configuration space fields.
    fn set_config(&mut self, offset: u32, flags: VhostUserConfigFlags, buf: &[u8]) -> Result<()>;

    /// Setup backend communication channel.
    fn set_backend_request_fd(&mut self, fd: &dyn AsRawFd) -> Result<()>;

    /// Retrieve a given dma-buf fd from a given backend
    fn get_shared_object(&mut self, uuid: &VhostUserSharedMsg) -> Result<File>;

    /// Retrieve shared buffer for inflight I/O tracking.
    fn get_inflight_fd(
        &mut self,
        inflight: &VhostUserInflight,
    ) -> Result<(VhostUserInflight, File)>;

    /// Set shared buffer for inflight I/O tracking.
    fn set_inflight_fd(&mut self, inflight: &VhostUserInflight, fd: RawFd) -> Result<()>;

    /// Query the maximum amount of memory slots supported by the backend.
    fn get_max_mem_slots(&mut self) -> Result<u64>;

    /// Add a new guest memory mapping for vhost to use.
    fn add_mem_region(&mut self, region: &VhostUserMemoryRegionInfo) -> Result<()>;

    /// Remove a guest memory mapping from vhost.
    fn remove_mem_region(&mut self, region: &VhostUserMemoryRegionInfo) -> Result<()>;

    /// Get the shared memory region configuration from the backend.
    fn get_shmem_config(&mut self) -> Result<VhostUserShMemConfig>;

    /// Begin transfer of internal state from/to the back-end
    /// for the purpose of migration.
    fn set_device_state_fd(
        &self,
        direction: VhostTransferStateDirection,
        phase: VhostTransferStatePhase,
        fd: OwnedFd,
    ) -> Result<Option<File>>;

    /// Inquire the back-end to report any potential errors
    /// that have occurred after transferring state from/to
    /// the back-end via vhost_set_device_state_fd().
    fn check_device_state(&self) -> Result<()>;

    /// Sends VHOST_USER_POSTCOPY_ADVISE msg to the backend
    /// initiating the beginning of the postcopy process.
    /// Backend will return a userfaultfd.
    #[cfg(feature = "postcopy")]
    fn postcopy_advise(&mut self) -> Result<File>;

    /// Sends VHOST_USER_POSTCOPY_LISTEN msg to the backend
    /// telling it to register its memory regions with
    /// userfaultfd previously received through the
    /// [`VhostUserFrontend::postcopy_advise`] call.
    #[cfg(feature = "postcopy")]
    fn postcopy_listen(&mut self) -> Result<()>;

    /// Sends VHOST_USER_POSTCOPY_END msg to the backend
    /// indicating the end of the postcopy process.
    /// Backend will destroy the userfaultfd object previously
    /// sent by [`VhostUserFrontend::postcopy_advise`].
    #[cfg(feature = "postcopy")]
    fn postcopy_end(&mut self) -> Result<()>;
}

fn error_code<T>(err: VhostUserError) -> Result<T> {
    Err(Error::VhostUserProtocol(err))
}

/// Struct for the vhost-user frontend endpoint.
#[derive(Clone)]
pub struct Frontend {
    node: Arc<Mutex<FrontendInternal>>,
}

impl Frontend {
    /// Create a new instance.
    fn new(ep: Endpoint<VhostUserMsgHeader<FrontendReq>>, max_queue_num: u64) -> Self {
        Frontend {
            node: Arc::new(Mutex::new(FrontendInternal {
                main_sock: ep,
                virtio_features: 0,
                acked_virtio_features: 0,
                protocol_features: 0,
                acked_protocol_features: 0,
                protocol_features_ready: false,
                max_queue_num,
                error: None,
                hdr_flags: VhostUserHeaderFlag::empty(),
            })),
        }
    }

    fn node(&self) -> MutexGuard<'_, FrontendInternal> {
        self.node.lock().unwrap()
    }

    /// Create a new instance from a Unix stream socket.
    pub fn from_stream(sock: UnixStream, max_queue_num: u64) -> Self {
        Self::new(
            Endpoint::<VhostUserMsgHeader<FrontendReq>>::from_stream(sock),
            max_queue_num,
        )
    }

    /// Create a new vhost-user frontend endpoint.
    ///
    /// Will retry as the backend may not be ready to accept the connection.
    ///
    /// # Arguments
    /// * `path` - path of Unix domain socket listener to connect to
    pub fn connect<P: AsRef<Path>>(path: P, max_queue_num: u64) -> Result<Self> {
        let mut retry_count = 5;
        let endpoint = loop {
            match Endpoint::<VhostUserMsgHeader<FrontendReq>>::connect(&path) {
                Ok(endpoint) => break Ok(endpoint),
                Err(e) => match &e {
                    VhostUserError::SocketConnect(why) => {
                        if why.kind() == std::io::ErrorKind::ConnectionRefused && retry_count > 0 {
                            std::thread::sleep(std::time::Duration::from_millis(100));
                            retry_count -= 1;
                            continue;
                        } else {
                            break Err(e);
                        }
                    }
                    _ => break Err(e),
                },
            }
        }?;

        Ok(Self::new(endpoint, max_queue_num))
    }

    /// Set the header flags that should be applied to all following messages.
    pub fn set_hdr_flags(&self, flags: VhostUserHeaderFlag) {
        let mut node = self.node();
        node.hdr_flags = flags;
    }
}

impl VhostBackend for Frontend {
    /// Get from the underlying vhost implementation the feature bitmask.
    fn get_features(&self) -> Result<u64> {
        let mut node = self.node();
        let hdr = node.send_request_header(FrontendReq::GET_FEATURES, None)?;
        let val = node.recv_reply::<VhostUserU64>(&hdr)?;
        node.virtio_features = val.value;
        Ok(node.virtio_features)
    }

    /// Enable features in the underlying vhost implementation using a bitmask.
    fn set_features(&self, features: u64) -> Result<()> {
        let mut node = self.node();
        let val = VhostUserU64::new(features);
        let hdr = node.send_request_with_body(FrontendReq::SET_FEATURES, &val, None)?;
        node.acked_virtio_features = features & node.virtio_features;
        node.wait_for_ack(&hdr).map_err(|e| e.into())
    }

    /// Set the current Frontend as an owner of the session.
    fn set_owner(&self) -> Result<()> {
        // We unwrap() the return value to assert that we are not expecting threads to ever fail
        // while holding the lock.
        let mut node = self.node();
        let hdr = node.send_request_header(FrontendReq::SET_OWNER, None)?;
        node.wait_for_ack(&hdr).map_err(|e| e.into())
    }

    fn reset_owner(&self) -> Result<()> {
        let mut node = self.node();
        let hdr = node.send_request_header(FrontendReq::RESET_OWNER, None)?;
        node.wait_for_ack(&hdr).map_err(|e| e.into())
    }

    /// Set the memory map regions on the backend so it can translate the vring
    /// addresses. In the ancillary data there is an array of file descriptors
    fn set_mem_table(&self, regions: &[VhostUserMemoryRegionInfo]) -> Result<()> {
        if regions.is_empty() || regions.len() > MAX_ATTACHED_FD_ENTRIES {
            return error_code(VhostUserError::InvalidParam);
        }

        let mut ctx = VhostUserMemoryContext::new();
        for region in regions.iter() {
            if region.memory_size == 0 || region.mmap_handle < 0 {
                return error_code(VhostUserError::InvalidParam);
            }

            ctx.append(&region.to_region(), region.mmap_handle);
        }

        let mut node = self.node();
        let body = VhostUserMemory::new(ctx.regions.len() as u32);
        // SAFETY: Safe because ctx.regions is a valid Vec() at this point.
        let (_, payload, _) = unsafe { ctx.regions.align_to::<u8>() };
        let hdr = node.send_request_with_payload(
            FrontendReq::SET_MEM_TABLE,
            &body,
            payload,
            Some(ctx.fds.as_slice()),
        )?;
        node.wait_for_ack(&hdr).map_err(|e| e.into())
    }

    // Clippy doesn't seem to know that if let with && is still experimental
    #[allow(clippy::unnecessary_unwrap)]
    fn set_log_base(&self, base: u64, region: Option<VhostUserDirtyLogRegion>) -> Result<()> {
        let mut node = self.node();
        let val = VhostUserU64::new(base);

        if node.acked_protocol_features & VhostUserProtocolFeatures::LOG_SHMFD.bits() != 0
            && region.is_some()
        {
            let region = region.unwrap();
            let log = VhostUserLog {
                mmap_size: region.mmap_size,
                mmap_offset: region.mmap_offset,
            };
            let hdr = node.send_request_with_body(
                FrontendReq::SET_LOG_BASE,
                &log,
                Some(&[region.mmap_handle]),
            )?;
            let _ = node.recv_reply::<VhostUserLog>(&hdr)?;
            Ok(())
        } else {
            let _ = node.send_request_with_body(FrontendReq::SET_LOG_BASE, &val, None)?;
            Ok(())
        }
    }

    fn set_log_fd(&self, fd: RawFd) -> Result<()> {
        let mut node = self.node();
        let fds = [fd];
        let hdr = node.send_request_header(FrontendReq::SET_LOG_FD, Some(&fds))?;
        node.wait_for_ack(&hdr).map_err(|e| e.into())
    }

    /// Set the size of the queue.
    fn set_vring_num(&self, queue_index: usize, num: u16) -> Result<()> {
        let mut node = self.node();
        if queue_index as u64 >= node.max_queue_num {
            return error_code(VhostUserError::InvalidParam);
        }

        let val = VhostUserVringState::new(queue_index as u32, num.into());
        let hdr = node.send_request_with_body(FrontendReq::SET_VRING_NUM, &val, None)?;
        node.wait_for_ack(&hdr).map_err(|e| e.into())
    }

    /// Sets the addresses of the different aspects of the vring.
    fn set_vring_addr(&self, queue_index: usize, config_data: &VringConfigData) -> Result<()> {
        let mut node = self.node();
        if queue_index as u64 >= node.max_queue_num
            || config_data.flags & !(VhostUserVringAddrFlags::all().bits()) != 0
        {
            return error_code(VhostUserError::InvalidParam);
        }

        let val = VhostUserVringAddr::from_config_data(queue_index as u32, config_data);
        let hdr = node.send_request_with_body(FrontendReq::SET_VRING_ADDR, &val, None)?;
        node.wait_for_ack(&hdr).map_err(|e| e.into())
    }

    /// Sets the base offset in the available vring.
    fn set_vring_base(&self, queue_index: usize, base: u16) -> Result<()> {
        let mut node = self.node();
        if queue_index as u64 >= node.max_queue_num {
            return error_code(VhostUserError::InvalidParam);
        }

        let val = VhostUserVringState::new(queue_index as u32, base.into());
        let hdr = node.send_request_with_body(FrontendReq::SET_VRING_BASE, &val, None)?;
        node.wait_for_ack(&hdr).map_err(|e| e.into())
    }

    fn get_vring_base(&self, queue_index: usize) -> Result<u32> {
        let mut node = self.node();
        if queue_index as u64 >= node.max_queue_num {
            return error_code(VhostUserError::InvalidParam);
        }

        let req = VhostUserVringState::new(queue_index as u32, 0);
        let hdr = node.send_request_with_body(FrontendReq::GET_VRING_BASE, &req, None)?;
        let reply = node.recv_reply::<VhostUserVringState>(&hdr)?;
        Ok(reply.num)
    }

    /// Set the event file descriptor to signal when buffers are used.
    /// Bits (0-7) of the payload contain the vring index. Bit 8 is the invalid FD flag. This flag
    /// is set when there is no file descriptor in the ancillary data. This signals that polling
    /// will be used instead of waiting for the call.
    fn set_vring_call(&self, queue_index: usize, fd: &EventFd) -> Result<()> {
        let mut node = self.node();
        if queue_index as u64 >= node.max_queue_num {
            return error_code(VhostUserError::InvalidParam);
        }
        let hdr =
            node.send_fd_for_vring(FrontendReq::SET_VRING_CALL, queue_index, fd.as_raw_fd())?;
        node.wait_for_ack(&hdr).map_err(|e| e.into())
    }

    /// Set the event file descriptor for adding buffers to the vring.
    /// Bits (0-7) of the payload contain the vring index. Bit 8 is the invalid FD flag. This flag
    /// is set when there is no file descriptor in the ancillary data. This signals that polling
    /// should be used instead of waiting for a kick.
    fn set_vring_kick(&self, queue_index: usize, fd: &EventFd) -> Result<()> {
        let mut node = self.node();
        if queue_index as u64 >= node.max_queue_num {
            return error_code(VhostUserError::InvalidParam);
        }
        let hdr =
            node.send_fd_for_vring(FrontendReq::SET_VRING_KICK, queue_index, fd.as_raw_fd())?;
        node.wait_for_ack(&hdr).map_err(|e| e.into())
    }

    /// Set the event file descriptor to signal when error occurs.
    /// Bits (0-7) of the payload contain the vring index. Bit 8 is the invalid FD flag. This flag
    /// is set when there is no file descriptor in the ancillary data.
    fn set_vring_err(&self, queue_index: usize, fd: &EventFd) -> Result<()> {
        let mut node = self.node();
        if queue_index as u64 >= node.max_queue_num {
            return error_code(VhostUserError::InvalidParam);
        }
        let hdr =
            node.send_fd_for_vring(FrontendReq::SET_VRING_ERR, queue_index, fd.as_raw_fd())?;
        node.wait_for_ack(&hdr).map_err(|e| e.into())
    }
}

impl VhostUserFrontend for Frontend {
    fn get_protocol_features(&mut self) -> Result<VhostUserProtocolFeatures> {
        let mut node = self.node();
        node.check_feature(VhostUserVirtioFeatures::PROTOCOL_FEATURES)?;
        let hdr = node.send_request_header(FrontendReq::GET_PROTOCOL_FEATURES, None)?;
        let val = node.recv_reply::<VhostUserU64>(&hdr)?;
        node.protocol_features = val.value;
        Ok(VhostUserProtocolFeatures::from_bits_truncate(
            node.protocol_features,
        ))
    }

    fn set_protocol_features(&mut self, features: VhostUserProtocolFeatures) -> Result<()> {
        let mut node = self.node();
        node.check_feature(VhostUserVirtioFeatures::PROTOCOL_FEATURES)?;
        let val = VhostUserU64::new(features.bits());
        let hdr = node.send_request_with_body(FrontendReq::SET_PROTOCOL_FEATURES, &val, None)?;
        // Don't wait for ACK here because the protocol feature negotiation process hasn't been
        // completed yet.
        node.acked_protocol_features = features.bits();
        node.protocol_features_ready = true;
        node.wait_for_ack(&hdr).map_err(|e| e.into())
    }

    fn get_queue_num(&mut self) -> Result<u64> {
        let mut node = self.node();
        node.check_proto_feature(VhostUserProtocolFeatures::MQ)?;

        let hdr = node.send_request_header(FrontendReq::GET_QUEUE_NUM, None)?;
        let val = node.recv_reply::<VhostUserU64>(&hdr)?;
        if val.value > VHOST_USER_MAX_VRINGS {
            return error_code(VhostUserError::InvalidMessage);
        }
        node.max_queue_num = val.value;
        Ok(node.max_queue_num)
    }

    fn reset_device(&mut self) -> Result<()> {
        let mut node = self.node();
        node.check_proto_feature(VhostUserProtocolFeatures::RESET_DEVICE)?;

        let hdr = node.send_request_header(FrontendReq::RESET_DEVICE, None)?;
        node.wait_for_ack(&hdr).map_err(|e| e.into())
    }

    fn set_vring_enable(&mut self, queue_index: usize, enable: bool) -> Result<()> {
        let mut node = self.node();
        // set_vring_enable() is supported only when PROTOCOL_FEATURES has been enabled.
        if node.acked_virtio_features & VhostUserVirtioFeatures::PROTOCOL_FEATURES.bits() == 0 {
            return error_code(VhostUserError::InactiveFeature(
                VhostUserVirtioFeatures::PROTOCOL_FEATURES,
            ));
        } else if queue_index as u64 >= node.max_queue_num {
            return error_code(VhostUserError::InvalidParam);
        }

        let flag = enable.into();
        let val = VhostUserVringState::new(queue_index as u32, flag);
        let hdr = node.send_request_with_body(FrontendReq::SET_VRING_ENABLE, &val, None)?;
        node.wait_for_ack(&hdr).map_err(|e| e.into())
    }

    fn get_config(
        &mut self,
        offset: u32,
        size: u32,
        flags: VhostUserConfigFlags,
        buf: &[u8],
    ) -> Result<(VhostUserConfig, VhostUserConfigPayload)> {
        let body = VhostUserConfig::new(offset, size, flags);
        if !body.is_valid() {
            return error_code(VhostUserError::InvalidParam);
        }

        let mut node = self.node();
        // depends on VhostUserProtocolFeatures::CONFIG
        node.check_proto_feature(VhostUserProtocolFeatures::CONFIG)?;

        // vhost-user spec states that:
        // "Frontend payload: virtio device config space"
        // "Backend payload: virtio device config space"
        let hdr = node.send_request_with_payload(FrontendReq::GET_CONFIG, &body, buf, None)?;
        let (body_reply, buf_reply, rfds) =
            node.recv_reply_with_payload::<VhostUserConfig>(&hdr)?;
        if rfds.is_some() {
            return error_code(VhostUserError::InvalidMessage);
        } else if body_reply.size == 0 {
            return error_code(VhostUserError::BackendInternalError);
        } else if body_reply.size != body.size
            || body_reply.size as usize != buf.len()
            || body_reply.offset != body.offset
        {
            return error_code(VhostUserError::InvalidMessage);
        }

        Ok((body_reply, buf_reply))
    }

    fn set_config(&mut self, offset: u32, flags: VhostUserConfigFlags, buf: &[u8]) -> Result<()> {
        if buf.len() > MAX_MSG_SIZE {
            return error_code(VhostUserError::InvalidParam);
        }
        let body = VhostUserConfig::new(offset, buf.len() as u32, flags);
        if !body.is_valid() {
            return error_code(VhostUserError::InvalidParam);
        }

        let mut node = self.node();
        // depends on VhostUserProtocolFeatures::CONFIG
        node.check_proto_feature(VhostUserProtocolFeatures::CONFIG)?;

        let hdr = node.send_request_with_payload(FrontendReq::SET_CONFIG, &body, buf, None)?;
        node.wait_for_ack(&hdr).map_err(|e| e.into())
    }

    fn set_backend_request_fd(&mut self, fd: &dyn AsRawFd) -> Result<()> {
        let mut node = self.node();
        node.check_proto_feature(VhostUserProtocolFeatures::BACKEND_REQ)?;
        let fds = [fd.as_raw_fd()];
        let hdr = node.send_request_header(FrontendReq::SET_BACKEND_REQ_FD, Some(&fds))?;
        node.wait_for_ack(&hdr).map_err(|e| e.into())
    }

    fn get_shared_object(&mut self, uuid: &VhostUserSharedMsg) -> Result<File> {
        let mut node = self.node();
        node.check_proto_feature(VhostUserProtocolFeatures::SHARED_OBJECT)?;
        if !uuid.is_valid() {
            return error_code(VhostUserError::InvalidParam);
        }
        let hdr = node.send_request_with_body(FrontendReq::GET_SHARED_OBJECT, uuid, None)?;
        let (_, files) = node.recv_reply_with_files::<VhostUserEmpty>(&hdr)?;

        match take_single_file(files) {
            Some(file) => Ok(file),
            None => error_code(VhostUserError::IncorrectFds),
        }
    }

    fn get_inflight_fd(
        &mut self,
        inflight: &VhostUserInflight,
    ) -> Result<(VhostUserInflight, File)> {
        let mut node = self.node();
        node.check_proto_feature(VhostUserProtocolFeatures::INFLIGHT_SHMFD)?;

        let hdr = node.send_request_with_body(FrontendReq::GET_INFLIGHT_FD, inflight, None)?;
        let (inflight, files) = node.recv_reply_with_files::<VhostUserInflight>(&hdr)?;

        match take_single_file(files) {
            Some(file) => Ok((inflight, file)),
            None => error_code(VhostUserError::IncorrectFds),
        }
    }

    fn set_inflight_fd(&mut self, inflight: &VhostUserInflight, fd: RawFd) -> Result<()> {
        let mut node = self.node();
        node.check_proto_feature(VhostUserProtocolFeatures::INFLIGHT_SHMFD)?;

        if inflight.mmap_size == 0 || inflight.num_queues == 0 || inflight.queue_size == 0 || fd < 0
        {
            return error_code(VhostUserError::InvalidParam);
        }

        let hdr =
            node.send_request_with_body(FrontendReq::SET_INFLIGHT_FD, inflight, Some(&[fd]))?;
        node.wait_for_ack(&hdr).map_err(|e| e.into())
    }

    fn get_max_mem_slots(&mut self) -> Result<u64> {
        let mut node = self.node();
        node.check_proto_feature(VhostUserProtocolFeatures::CONFIGURE_MEM_SLOTS)?;

        let hdr = node.send_request_header(FrontendReq::GET_MAX_MEM_SLOTS, None)?;
        let val = node.recv_reply::<VhostUserU64>(&hdr)?;

        Ok(val.value)
    }

    fn add_mem_region(&mut self, region: &VhostUserMemoryRegionInfo) -> Result<()> {
        let mut node = self.node();
        node.check_proto_feature(VhostUserProtocolFeatures::CONFIGURE_MEM_SLOTS)?;
        if region.memory_size == 0 || region.mmap_handle < 0 {
            return error_code(VhostUserError::InvalidParam);
        }

        let body = region.to_single_region();
        let fds = [region.mmap_handle];
        let hdr = node.send_request_with_body(FrontendReq::ADD_MEM_REG, &body, Some(&fds))?;
        node.wait_for_ack(&hdr).map_err(|e| e.into())
    }

    fn remove_mem_region(&mut self, region: &VhostUserMemoryRegionInfo) -> Result<()> {
        let mut node = self.node();
        node.check_proto_feature(VhostUserProtocolFeatures::CONFIGURE_MEM_SLOTS)?;
        if region.memory_size == 0 {
            return error_code(VhostUserError::InvalidParam);
        }

        let body = region.to_single_region();
        let hdr = node.send_request_with_body(FrontendReq::REM_MEM_REG, &body, None)?;
        node.wait_for_ack(&hdr).map_err(|e| e.into())
    }

    fn get_shmem_config(&mut self) -> Result<VhostUserShMemConfig> {
        let mut node = self.node();
        node.check_proto_feature(VhostUserProtocolFeatures::SHMEM)?;

        let hdr = node.send_request_header(FrontendReq::GET_SHMEM_CONFIG, None)?;
        let config = node.recv_reply::<VhostUserShMemConfig>(&hdr)?;

        Ok(config)
    }

    fn set_device_state_fd(
        &self,
        direction: VhostTransferStateDirection,
        phase: VhostTransferStatePhase,
        fd: OwnedFd,
    ) -> Result<Option<File>> {
        let mut node = self.node();
        node.check_proto_feature(VhostUserProtocolFeatures::DEVICE_STATE)?;

        let body = VhostUserTransferDeviceState::new(direction, phase);
        if !body.is_valid() {
            return error_code(VhostUserError::InvalidParam);
        }

        let hdr = node.send_request_with_body(
            FrontendReq::SET_DEVICE_STATE_FD,
            &body,
            Some(&[fd.as_raw_fd()]),
        )?;

        let (body, files) = node.recv_reply_with_optional_files::<VhostUserU64>(&hdr)?;
        let msg = body.value;
        if msg == 0x100 && files.is_none() {
            return Ok(None);
        } else if msg == 0 && files.is_some() {
            return match take_single_file(files) {
                Some(file) => Ok(Some(file)),
                None => error_code(VhostUserError::IncorrectFds),
            };
        }

        error_code(VhostUserError::BackendInternalError)
    }

    fn check_device_state(&self) -> Result<()> {
        let mut node = self.node();
        node.check_proto_feature(VhostUserProtocolFeatures::DEVICE_STATE)?;
        let hdr = node.send_request_header(FrontendReq::CHECK_DEVICE_STATE, None)?;
        let body = node.recv_reply::<VhostUserU64>(&hdr)?;

        if body.value != 0 {
            return error_code(VhostUserError::BackendInternalError);
        }

        Ok(())
    }

    #[cfg(feature = "postcopy")]
    fn postcopy_advise(&mut self) -> Result<File> {
        let mut node = self.node();
        node.check_proto_feature(VhostUserProtocolFeatures::PAGEFAULT)?;

        let hdr = node.send_request_header(FrontendReq::POSTCOPY_ADVISE, None)?;
        let (_, files) = node.recv_reply_with_files::<VhostUserEmpty>(&hdr)?;

        match take_single_file(files) {
            Some(file) => Ok(file),
            None => error_code(VhostUserError::IncorrectFds),
        }
    }

    #[cfg(feature = "postcopy")]
    fn postcopy_listen(&mut self) -> Result<()> {
        let mut node = self.node();
        node.check_proto_feature(VhostUserProtocolFeatures::PAGEFAULT)?;
        let hdr = node.send_request_header(FrontendReq::POSTCOPY_LISTEN, None)?;
        node.wait_for_ack(&hdr).map_err(|e| e.into())
    }

    #[cfg(feature = "postcopy")]
    fn postcopy_end(&mut self) -> Result<()> {
        let mut node = self.node();
        node.check_proto_feature(VhostUserProtocolFeatures::PAGEFAULT)?;
        let hdr = node.send_request_header(FrontendReq::POSTCOPY_END, None)?;
        node.wait_for_ack(&hdr).map_err(|e| e.into())
    }
}

impl AsRawFd for Frontend {
    fn as_raw_fd(&self) -> RawFd {
        let node = self.node();
        node.main_sock.as_raw_fd()
    }
}

/// Context object to pass guest memory configuration to VhostUserFrontend::set_mem_table().
struct VhostUserMemoryContext {
    regions: VhostUserMemoryPayload,
    fds: Vec<RawFd>,
}

impl VhostUserMemoryContext {
    /// Create a context object.
    pub fn new() -> Self {
        VhostUserMemoryContext {
            regions: VhostUserMemoryPayload::new(),
            fds: Vec::new(),
        }
    }

    /// Append a user memory region and corresponding RawFd into the context object.
    pub fn append(&mut self, region: &VhostUserMemoryRegion, fd: RawFd) {
        self.regions.push(*region);
        self.fds.push(fd);
    }
}

struct FrontendInternal {
    // Used to send requests to the backend.
    main_sock: Endpoint<VhostUserMsgHeader<FrontendReq>>,
    // Cached virtio features from the backend.
    virtio_features: u64,
    // Cached acked virtio features from the driver.
    acked_virtio_features: u64,
    // Cached vhost-user protocol features from the backend.
    protocol_features: u64,
    // Cached vhost-user protocol features.
    acked_protocol_features: u64,
    // Cached vhost-user protocol features are ready to use.
    protocol_features_ready: bool,
    // Cached maxinum number of queues supported from the backend.
    max_queue_num: u64,
    // Internal flag to mark failure state.
    error: Option<i32>,
    // List of header flags.
    hdr_flags: VhostUserHeaderFlag,
}

impl FrontendInternal {
    fn send_request_header(
        &mut self,
        code: FrontendReq,
        fds: Option<&[RawFd]>,
    ) -> VhostUserResult<VhostUserMsgHeader<FrontendReq>> {
        self.check_state()?;
        let hdr = self.new_request_header(code, 0);
        self.main_sock.send_header(&hdr, fds)?;
        Ok(hdr)
    }

    fn send_request_with_body<T: ByteValued>(
        &mut self,
        code: FrontendReq,
        msg: &T,
        fds: Option<&[RawFd]>,
    ) -> VhostUserResult<VhostUserMsgHeader<FrontendReq>> {
        if mem::size_of::<T>() > MAX_MSG_SIZE {
            return Err(VhostUserError::InvalidParam);
        }
        self.check_state()?;

        let hdr = self.new_request_header(code, mem::size_of::<T>() as u32);
        self.main_sock.send_message(&hdr, msg, fds)?;
        Ok(hdr)
    }

    fn send_request_with_payload<T: ByteValued>(
        &mut self,
        code: FrontendReq,
        msg: &T,
        payload: &[u8],
        fds: Option<&[RawFd]>,
    ) -> VhostUserResult<VhostUserMsgHeader<FrontendReq>> {
        let len = mem::size_of::<T>() + payload.len();
        if len > MAX_MSG_SIZE {
            return Err(VhostUserError::InvalidParam);
        }
        if let Some(fd_arr) = fds {
            if fd_arr.len() > MAX_ATTACHED_FD_ENTRIES {
                return Err(VhostUserError::InvalidParam);
            }
        }
        self.check_state()?;

        let hdr = self.new_request_header(code, len as u32);
        self.main_sock
            .send_message_with_payload(&hdr, msg, payload, fds)?;
        Ok(hdr)
    }

    fn send_fd_for_vring(
        &mut self,
        code: FrontendReq,
        queue_index: usize,
        fd: RawFd,
    ) -> VhostUserResult<VhostUserMsgHeader<FrontendReq>> {
        if queue_index as u64 >= self.max_queue_num {
            return Err(VhostUserError::InvalidParam);
        }
        self.check_state()?;

        // Bits (0-7) of the payload contain the vring index. Bit 8 is the invalid FD flag.
        // This flag is set when there is no file descriptor in the ancillary data. This signals
        // that polling will be used instead of waiting for the call.
        let msg = VhostUserU64::new(queue_index as u64);
        let hdr = self.new_request_header(code, mem::size_of::<VhostUserU64>() as u32);
        self.main_sock.send_message(&hdr, &msg, Some(&[fd]))?;
        Ok(hdr)
    }

    fn recv_reply<T: ByteValued + Sized + VhostUserMsgValidator + Default>(
        &mut self,
        hdr: &VhostUserMsgHeader<FrontendReq>,
    ) -> VhostUserResult<T> {
        if mem::size_of::<T>() > MAX_MSG_SIZE || hdr.is_reply() {
            return Err(VhostUserError::InvalidParam);
        }
        self.check_state()?;

        let (reply, body, rfds) = self.main_sock.recv_body::<T>()?;
        if !reply.is_reply_for(hdr) || rfds.is_some() || !body.is_valid() {
            return Err(VhostUserError::InvalidMessage);
        }
        Ok(body)
    }

    fn recv_reply_with_optional_files<T: ByteValued + Sized + VhostUserMsgValidator + Default>(
        &mut self,
        hdr: &VhostUserMsgHeader<FrontendReq>,
    ) -> VhostUserResult<(T, Option<Vec<File>>)> {
        if mem::size_of::<T>() > MAX_MSG_SIZE || hdr.is_reply() {
            return Err(VhostUserError::InvalidParam);
        }
        self.check_state()?;

        let (reply, body, files) = self.main_sock.recv_body::<T>()?;
        if !reply.is_reply_for(hdr) || !body.is_valid() {
            return Err(VhostUserError::InvalidMessage);
        }
        Ok((body, files))
    }

    fn recv_reply_with_files<T: ByteValued + Sized + VhostUserMsgValidator + Default>(
        &mut self,
        hdr: &VhostUserMsgHeader<FrontendReq>,
    ) -> VhostUserResult<(T, Option<Vec<File>>)> {
        let (body, files) = self.recv_reply_with_optional_files(hdr)?;
        if files.is_none() {
            return Err(VhostUserError::InvalidMessage);
        }

        Ok((body, files))
    }

    fn recv_reply_with_payload<T: ByteValued + Sized + VhostUserMsgValidator + Default>(
        &mut self,
        hdr: &VhostUserMsgHeader<FrontendReq>,
    ) -> VhostUserResult<(T, Vec<u8>, Option<Vec<File>>)> {
        if mem::size_of::<T>() > MAX_MSG_SIZE
            || hdr.get_size() as usize <= mem::size_of::<T>()
            || hdr.get_size() as usize > MAX_MSG_SIZE
            || hdr.is_reply()
        {
            return Err(VhostUserError::InvalidParam);
        }
        self.check_state()?;

        let mut buf: Vec<u8> = vec![0; hdr.get_size() as usize - mem::size_of::<T>()];
        let (reply, body, bytes, files) = self.main_sock.recv_payload_into_buf::<T>(&mut buf)?;
        if !reply.is_reply_for(hdr)
            || reply.get_size() as usize != mem::size_of::<T>() + bytes
            || files.is_some()
            || !body.is_valid()
            || bytes != buf.len()
        {
            return Err(VhostUserError::InvalidMessage);
        }

        Ok((body, buf, files))
    }

    fn wait_for_ack(&mut self, hdr: &VhostUserMsgHeader<FrontendReq>) -> VhostUserResult<()> {
        if self.acked_protocol_features & VhostUserProtocolFeatures::REPLY_ACK.bits() == 0
            || !hdr.is_need_reply()
        {
            return Ok(());
        }
        self.check_state()?;

        let (reply, body, rfds) = self.main_sock.recv_body::<VhostUserU64>()?;
        if !reply.is_reply_for(hdr) || rfds.is_some() || !body.is_valid() {
            return Err(VhostUserError::InvalidMessage);
        }
        if body.value != 0 {
            return Err(VhostUserError::BackendInternalError);
        }
        Ok(())
    }

    fn check_feature(&self, feat: VhostUserVirtioFeatures) -> VhostUserResult<()> {
        if self.virtio_features & feat.bits() != 0 {
            Ok(())
        } else {
            Err(VhostUserError::InactiveFeature(feat))
        }
    }

    fn check_proto_feature(&self, feat: VhostUserProtocolFeatures) -> VhostUserResult<()> {
        if self.acked_protocol_features & feat.bits() != 0 {
            Ok(())
        } else {
            Err(VhostUserError::InactiveOperation(feat))
        }
    }

    fn check_state(&self) -> VhostUserResult<()> {
        match self.error {
            Some(e) => Err(VhostUserError::SocketBroken(
                std::io::Error::from_raw_os_error(e),
            )),
            None => Ok(()),
        }
    }

    #[inline]
    fn new_request_header(
        &self,
        request: FrontendReq,
        size: u32,
    ) -> VhostUserMsgHeader<FrontendReq> {
        VhostUserMsgHeader::new(request, self.hdr_flags.bits() | 0x1, size)
    }
}

#[cfg(test)]
mod tests {
    use super::super::connection::Listener;
    use super::*;
    use vmm_sys_util::rand::rand_alphanumerics;

    use std::path::PathBuf;

    const INVALID_PROTOCOL_FEATURE: u64 = 1 << 63;

    fn temp_path() -> PathBuf {
        PathBuf::from(format!(
            "/tmp/vhost_test_{}",
            rand_alphanumerics(8).to_str().unwrap()
        ))
    }

    fn create_pair<P: AsRef<Path>>(
        path: P,
    ) -> (Frontend, Endpoint<VhostUserMsgHeader<FrontendReq>>) {
        let listener = Listener::new(&path, true).unwrap();
        listener.set_nonblocking(true).unwrap();
        let frontend = Frontend::connect(path, 2).unwrap();
        let backend = listener.accept().unwrap().unwrap();
        (frontend, Endpoint::from_stream(backend))
    }

    #[test]
    fn create_frontend() {
        let path = temp_path();
        let listener = Listener::new(&path, true).unwrap();
        listener.set_nonblocking(true).unwrap();

        let frontend = Frontend::connect(&path, 1).unwrap();
        let mut backend = Endpoint::<VhostUserMsgHeader<FrontendReq>>::from_stream(
            listener.accept().unwrap().unwrap(),
        );

        assert!(frontend.as_raw_fd() > 0);
        // Send two messages continuously
        frontend.set_owner().unwrap();
        frontend.reset_owner().unwrap();

        let (hdr, rfds) = backend.recv_header().unwrap();
        assert_eq!(hdr.get_code().unwrap(), FrontendReq::SET_OWNER);
        assert_eq!(hdr.get_size(), 0);
        assert_eq!(hdr.get_version(), 0x1);
        assert!(rfds.is_none());

        let (hdr, rfds) = backend.recv_header().unwrap();
        assert_eq!(hdr.get_code().unwrap(), FrontendReq::RESET_OWNER);
        assert_eq!(hdr.get_size(), 0);
        assert_eq!(hdr.get_version(), 0x1);
        assert!(rfds.is_none());
    }

    #[test]
    fn test_create_failure() {
        let path = temp_path();
        let _ = Listener::new(&path, true).unwrap();
        let _ = Listener::new(&path, false).is_err();
        assert!(Frontend::connect(&path, 1).is_err());

        let listener = Listener::new(&path, true).unwrap();
        assert!(Listener::new(&path, false).is_err());
        listener.set_nonblocking(true).unwrap();

        let _frontend = Frontend::connect(&path, 1).unwrap();
        let _backend = listener.accept().unwrap().unwrap();
    }

    #[test]
    fn test_features() {
        let path = temp_path();
        let (frontend, mut peer) = create_pair(path);

        frontend.set_owner().unwrap();
        let (hdr, rfds) = peer.recv_header().unwrap();
        assert_eq!(hdr.get_code().unwrap(), FrontendReq::SET_OWNER);
        assert_eq!(hdr.get_size(), 0);
        assert_eq!(hdr.get_version(), 0x1);
        assert!(rfds.is_none());

        let hdr = VhostUserMsgHeader::new(FrontendReq::GET_FEATURES, 0x4, 8);
        let msg = VhostUserU64::new(0x15);
        peer.send_message(&hdr, &msg, None).unwrap();
        let features = frontend.get_features().unwrap();
        assert_eq!(features, 0x15u64);
        let (_hdr, rfds) = peer.recv_header().unwrap();
        assert!(rfds.is_none());

        let hdr = VhostUserMsgHeader::new(FrontendReq::SET_FEATURES, 0x4, 8);
        let msg = VhostUserU64::new(0x15);
        peer.send_message(&hdr, &msg, None).unwrap();
        frontend.set_features(0x15).unwrap();
        let (_hdr, msg, rfds) = peer.recv_body::<VhostUserU64>().unwrap();
        assert!(rfds.is_none());
        let val = msg.value;
        assert_eq!(val, 0x15);

        let hdr = VhostUserMsgHeader::new(FrontendReq::GET_FEATURES, 0x4, 8);
        let msg = 0x15u32;
        peer.send_message(&hdr, &msg, None).unwrap();
        assert!(frontend.get_features().is_err());
    }

    #[test]
    fn test_protocol_features() {
        let path = temp_path();
        let (mut frontend, mut peer) = create_pair(path);

        frontend.set_owner().unwrap();
        let (hdr, rfds) = peer.recv_header().unwrap();
        assert_eq!(hdr.get_code().unwrap(), FrontendReq::SET_OWNER);
        assert!(rfds.is_none());

        assert!(frontend.get_protocol_features().is_err());
        assert!(frontend
            .set_protocol_features(VhostUserProtocolFeatures::all())
            .is_err());

        let vfeatures = 0x15 | VhostUserVirtioFeatures::PROTOCOL_FEATURES.bits();
        let hdr = VhostUserMsgHeader::new(FrontendReq::GET_FEATURES, 0x4, 8);
        let msg = VhostUserU64::new(vfeatures);
        peer.send_message(&hdr, &msg, None).unwrap();
        let features = frontend.get_features().unwrap();
        assert_eq!(features, vfeatures);
        let (_hdr, rfds) = peer.recv_header().unwrap();
        assert!(rfds.is_none());

        frontend.set_features(vfeatures).unwrap();
        let (_hdr, msg, rfds) = peer.recv_body::<VhostUserU64>().unwrap();
        assert!(rfds.is_none());
        let val = msg.value;
        assert_eq!(val, vfeatures);

        let pfeatures = VhostUserProtocolFeatures::all();
        let hdr = VhostUserMsgHeader::new(FrontendReq::GET_PROTOCOL_FEATURES, 0x4, 8);
        // Unknown feature bits should be ignored.
        let msg = VhostUserU64::new(pfeatures.bits() | INVALID_PROTOCOL_FEATURE);
        peer.send_message(&hdr, &msg, None).unwrap();
        let features = frontend.get_protocol_features().unwrap();
        assert_eq!(features, pfeatures);
        let (_hdr, rfds) = peer.recv_header().unwrap();
        assert!(rfds.is_none());

        frontend.set_protocol_features(pfeatures).unwrap();
        let (_hdr, msg, rfds) = peer.recv_body::<VhostUserU64>().unwrap();
        assert!(rfds.is_none());
        let val = msg.value;
        assert_eq!(val, pfeatures.bits());

        let hdr = VhostUserMsgHeader::new(FrontendReq::SET_PROTOCOL_FEATURES, 0x4, 8);
        let msg = VhostUserU64::new(pfeatures.bits());
        peer.send_message(&hdr, &msg, None).unwrap();
        assert!(frontend.get_protocol_features().is_err());
    }

    #[test]
    fn test_frontend_set_config_negative() {
        let path = temp_path();
        let (mut frontend, _peer) = create_pair(path);
        let buf = vec![0x0; MAX_MSG_SIZE + 1];

        frontend
            .set_config(0x100, VhostUserConfigFlags::WRITABLE, &buf[0..4])
            .unwrap_err();

        {
            let mut node = frontend.node();
            node.virtio_features = 0xffff_ffff;
            node.acked_virtio_features = 0xffff_ffff;
            node.protocol_features = 0xffff_ffff;
            node.acked_protocol_features = 0xffff_ffff;
        }

        frontend
            .set_config(0, VhostUserConfigFlags::WRITABLE, &buf[0..4])
            .unwrap();
        frontend
            .set_config(
                VHOST_USER_CONFIG_SIZE,
                VhostUserConfigFlags::WRITABLE,
                &buf[0..4],
            )
            .unwrap_err();
        frontend
            .set_config(0x1000, VhostUserConfigFlags::WRITABLE, &buf[0..4])
            .unwrap_err();
        frontend
            .set_config(
                0x100,
                // This is a negative test, so we are setting unexpected flags.
                VhostUserConfigFlags::from_bits_retain(0xffff_ffff),
                &buf[0..4],
            )
            .unwrap_err();
        frontend
            .set_config(VHOST_USER_CONFIG_SIZE, VhostUserConfigFlags::WRITABLE, &buf)
            .unwrap_err();
        frontend
            .set_config(VHOST_USER_CONFIG_SIZE, VhostUserConfigFlags::WRITABLE, &[])
            .unwrap_err();
    }

    fn create_pair2() -> (Frontend, Endpoint<VhostUserMsgHeader<FrontendReq>>) {
        let path = temp_path();
        let (frontend, peer) = create_pair(path);

        {
            let mut node = frontend.node();
            node.virtio_features = 0xffff_ffff;
            node.acked_virtio_features = 0xffff_ffff;
            node.protocol_features = 0xffff_ffff;
            node.acked_protocol_features = 0xffff_ffff;
        }

        (frontend, peer)
    }

    #[test]
    fn test_frontend_get_config_negative0() {
        let (mut frontend, mut peer) = create_pair2();
        let buf = vec![0x0; MAX_MSG_SIZE + 1];

        let mut hdr = VhostUserMsgHeader::new(FrontendReq::GET_CONFIG, 0x4, 16);
        let msg = VhostUserConfig::new(0x100, 4, VhostUserConfigFlags::empty());
        peer.send_message_with_payload(&hdr, &msg, &buf[0..4], None)
            .unwrap();
        assert!(frontend
            .get_config(0x100, 4, VhostUserConfigFlags::WRITABLE, &buf[0..4])
            .is_ok());

        hdr.set_code(FrontendReq::GET_FEATURES);
        peer.send_message_with_payload(&hdr, &msg, &buf[0..4], None)
            .unwrap();
        assert!(frontend
            .get_config(0x100, 4, VhostUserConfigFlags::WRITABLE, &buf[0..4])
            .is_err());
        hdr.set_code(FrontendReq::GET_CONFIG);
    }

    #[test]
    fn test_frontend_get_config_negative1() {
        let (mut frontend, mut peer) = create_pair2();
        let buf = vec![0x0; MAX_MSG_SIZE + 1];

        let mut hdr = VhostUserMsgHeader::new(FrontendReq::GET_CONFIG, 0x4, 16);
        let msg = VhostUserConfig::new(0x100, 4, VhostUserConfigFlags::empty());
        peer.send_message_with_payload(&hdr, &msg, &buf[0..4], None)
            .unwrap();
        assert!(frontend
            .get_config(0x100, 4, VhostUserConfigFlags::WRITABLE, &buf[0..4])
            .is_ok());

        hdr.set_reply(false);
        peer.send_message_with_payload(&hdr, &msg, &buf[0..4], None)
            .unwrap();
        assert!(frontend
            .get_config(0x100, 4, VhostUserConfigFlags::WRITABLE, &buf[0..4])
            .is_err());
    }

    #[test]
    fn test_frontend_get_config_negative2() {
        let (mut frontend, mut peer) = create_pair2();
        let buf = vec![0x0; MAX_MSG_SIZE + 1];

        let hdr = VhostUserMsgHeader::new(FrontendReq::GET_CONFIG, 0x4, 16);
        let msg = VhostUserConfig::new(0x100, 4, VhostUserConfigFlags::empty());
        peer.send_message_with_payload(&hdr, &msg, &buf[0..4], None)
            .unwrap();
        assert!(frontend
            .get_config(0x100, 4, VhostUserConfigFlags::WRITABLE, &buf[0..4])
            .is_ok());
    }

    #[test]
    fn test_frontend_get_config_negative3() {
        let (mut frontend, mut peer) = create_pair2();
        let buf = vec![0x0; MAX_MSG_SIZE + 1];

        let hdr = VhostUserMsgHeader::new(FrontendReq::GET_CONFIG, 0x4, 16);
        let mut msg = VhostUserConfig::new(0x100, 4, VhostUserConfigFlags::empty());
        peer.send_message_with_payload(&hdr, &msg, &buf[0..4], None)
            .unwrap();
        assert!(frontend
            .get_config(0x100, 4, VhostUserConfigFlags::WRITABLE, &buf[0..4])
            .is_ok());

        msg.offset = 0;
        peer.send_message_with_payload(&hdr, &msg, &buf[0..4], None)
            .unwrap();
        assert!(frontend
            .get_config(0x100, 4, VhostUserConfigFlags::WRITABLE, &buf[0..4])
            .is_err());
    }

    #[test]
    fn test_frontend_get_config_negative4() {
        let (mut frontend, mut peer) = create_pair2();
        let buf = vec![0x0; MAX_MSG_SIZE + 1];

        let hdr = VhostUserMsgHeader::new(FrontendReq::GET_CONFIG, 0x4, 16);
        let mut msg = VhostUserConfig::new(0x100, 4, VhostUserConfigFlags::empty());
        peer.send_message_with_payload(&hdr, &msg, &buf[0..4], None)
            .unwrap();
        assert!(frontend
            .get_config(0x100, 4, VhostUserConfigFlags::WRITABLE, &buf[0..4])
            .is_ok());

        msg.offset = 0x101;
        peer.send_message_with_payload(&hdr, &msg, &buf[0..4], None)
            .unwrap();
        assert!(frontend
            .get_config(0x100, 4, VhostUserConfigFlags::WRITABLE, &buf[0..4])
            .is_err());
    }

    #[test]
    fn test_frontend_get_config_negative5() {
        let (mut frontend, mut peer) = create_pair2();
        let buf = vec![0x0; MAX_MSG_SIZE + 1];

        let hdr = VhostUserMsgHeader::new(FrontendReq::GET_CONFIG, 0x4, 16);
        let mut msg = VhostUserConfig::new(0x100, 4, VhostUserConfigFlags::empty());
        peer.send_message_with_payload(&hdr, &msg, &buf[0..4], None)
            .unwrap();
        assert!(frontend
            .get_config(0x100, 4, VhostUserConfigFlags::WRITABLE, &buf[0..4])
            .is_ok());

        msg.offset = (MAX_MSG_SIZE + 1) as u32;
        peer.send_message_with_payload(&hdr, &msg, &buf[0..4], None)
            .unwrap();
        assert!(frontend
            .get_config(0x100, 4, VhostUserConfigFlags::WRITABLE, &buf[0..4])
            .is_err());
    }

    #[test]
    fn test_frontend_get_config_negative6() {
        let (mut frontend, mut peer) = create_pair2();
        let buf = vec![0x0; MAX_MSG_SIZE + 1];

        let hdr = VhostUserMsgHeader::new(FrontendReq::GET_CONFIG, 0x4, 16);
        let mut msg = VhostUserConfig::new(0x100, 4, VhostUserConfigFlags::empty());
        peer.send_message_with_payload(&hdr, &msg, &buf[0..4], None)
            .unwrap();
        assert!(frontend
            .get_config(0x100, 4, VhostUserConfigFlags::WRITABLE, &buf[0..4])
            .is_ok());

        msg.size = 6;
        peer.send_message_with_payload(&hdr, &msg, &buf[0..6], None)
            .unwrap();
        assert!(frontend
            .get_config(0x100, 4, VhostUserConfigFlags::WRITABLE, &buf[0..4])
            .is_err());
    }

    #[test]
    fn test_maset_set_mem_table_failure() {
        let (frontend, _peer) = create_pair2();

        frontend.set_mem_table(&[]).unwrap_err();
        let tables = vec![VhostUserMemoryRegionInfo::default(); MAX_ATTACHED_FD_ENTRIES + 1];
        frontend.set_mem_table(&tables).unwrap_err();
    }

    #[test]
    fn test_frontend_get_shmem_config() {
        let (mut frontend, mut peer) = create_pair2();

        let expected_config = VhostUserShMemConfig::new(2, &[0x1000, 0x2000]);
        let hdr = VhostUserMsgHeader::new(
            FrontendReq::GET_SHMEM_CONFIG,
            0x4,
            std::mem::size_of::<VhostUserShMemConfig>() as u32,
        );
        peer.send_message(&hdr, &expected_config, None).unwrap();

        let config = frontend.get_shmem_config().unwrap();
        assert_eq!(config.nregions, 2);
        assert_eq!(config.memory_sizes[0], 0x1000);
        assert_eq!(config.memory_sizes[1], 0x2000);

        let (recv_hdr, rfds) = peer.recv_header().unwrap();
        assert_eq!(recv_hdr.get_code().unwrap(), FrontendReq::GET_SHMEM_CONFIG);
        assert!(rfds.is_none());
    }

    #[test]
    fn test_frontend_get_shmem_config_no_regions() {
        let (mut frontend, mut peer) = create_pair2();

        let expected_config = VhostUserShMemConfig::default();
        let hdr = VhostUserMsgHeader::new(
            FrontendReq::GET_SHMEM_CONFIG,
            0x4,
            std::mem::size_of::<VhostUserShMemConfig>() as u32,
        );
        peer.send_message(&hdr, &expected_config, None).unwrap();

        let config = frontend.get_shmem_config().unwrap();
        assert_eq!(config.nregions, 0);
        for i in 0..256 {
            assert_eq!(config.memory_sizes[i], 0);
        }
    }

    #[test]
    fn test_frontend_set_device_state_fd_no_return_fd() {
        let (frontend, mut peer) = create_pair2();

        // Backend replies: success + "invalid FD" flag (bit 8 set), no returned FD.
        let reply_hdr = VhostUserMsgHeader::new(
            FrontendReq::SET_DEVICE_STATE_FD,
            0x4,
            std::mem::size_of::<VhostUserU64>() as u32,
        );
        let reply_body = VhostUserU64::new(0x100);
        peer.send_message(&reply_hdr, &reply_body, None).unwrap();

        let file = File::open("/dev/null").unwrap();
        let owned_fd = file.into();
        let res = frontend
            .set_device_state_fd(
                VhostTransferStateDirection::SAVE,
                VhostTransferStatePhase::STOPPED,
                owned_fd,
            )
            .unwrap();
        assert!(res.is_none());
    }

    #[test]
    fn test_frontend_set_device_state_fd_with_return_fd() {
        let (frontend, mut peer) = create_pair2();

        // Backend replies: success + returns a single FD.
        let reply_hdr = VhostUserMsgHeader::new(
            FrontendReq::SET_DEVICE_STATE_FD,
            0x4,
            std::mem::size_of::<VhostUserU64>() as u32,
        );
        let reply_body = VhostUserU64::new(0);
        let return_file = File::open("/dev/null").unwrap();
        peer.send_message(&reply_hdr, &reply_body, Some(&[return_file.as_raw_fd()]))
            .unwrap();

        let file = File::open("/dev/null").unwrap();
        let owned_fd = file.into();
        let res = frontend
            .set_device_state_fd(
                VhostTransferStateDirection::LOAD,
                VhostTransferStatePhase::STOPPED,
                owned_fd,
            )
            .unwrap();
        let returned = res.unwrap();
        assert!(returned.as_raw_fd() > 0);
    }

    #[test]
    fn test_frontend_check_device_state() {
        let (frontend, mut peer) = create_pair2();

        let reply_hdr = VhostUserMsgHeader::new(
            FrontendReq::CHECK_DEVICE_STATE,
            0x4,
            std::mem::size_of::<VhostUserU64>() as u32,
        );
        let reply_body = VhostUserU64::new(123);
        peer.send_message(&reply_hdr, &reply_body, None).unwrap();
        assert!(frontend.check_device_state().is_err());

        let reply_body = VhostUserU64::new(0);
        peer.send_message(&reply_hdr, &reply_body, None).unwrap();
        assert!(frontend.check_device_state().is_ok());
    }
}