-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathpoller.rs
More file actions
1749 lines (1513 loc) · 62.4 KB
/
poller.rs
File metadata and controls
1749 lines (1513 loc) · 62.4 KB
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::collections::VecDeque;
use std::ffi::c_void;
use std::io::ErrorKind;
use std::io::Read;
use std::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, OwnedFd, RawFd};
use std::sync::Arc;
use std::thread::JoinHandle;
use iddqd::IdHashMap;
use nix::poll::PollFlags;
use slog::{error, info, warn, Logger};
use crate::hw::virtio::vsock::VsockVq;
use crate::hw::virtio::vsock::VSOCK_RX_QUEUE;
use crate::hw::virtio::vsock::VSOCK_TX_QUEUE;
use crate::vsock::packet::VsockPacket;
use crate::vsock::packet::VsockPacketFlags;
use crate::vsock::packet::VsockSocketType;
use crate::vsock::probes;
use crate::vsock::proxy::ConnKey;
use crate::vsock::proxy::VsockPortMapping;
use crate::vsock::proxy::VsockProxyConn;
use crate::vsock::GuestCid;
use crate::vsock::VSOCK_HOST_CID;
use super::packet::VsockGuestAddr;
use super::packet::VsockPacketOp;
#[repr(usize)]
enum VsockEvent {
TxQueue = 0,
RxQueue,
Shutdown,
}
pub struct VsockPollerNotify {
port_fd: Arc<OwnedFd>,
}
impl VsockPollerNotify {
fn port_fd(&self) -> BorrowedFd<'_> {
self.port_fd.as_fd()
}
fn port_send(&self, event: VsockEvent) -> std::io::Result<()> {
let ret = unsafe {
libc::port_send(self.port_fd().as_raw_fd(), 0, event as usize as _)
};
if ret == 0 {
Ok(())
} else {
Err(std::io::Error::last_os_error())
}
}
pub fn queue_notify(&self, id: u16) -> std::io::Result<()> {
match id {
VSOCK_RX_QUEUE => self.port_send(VsockEvent::RxQueue),
VSOCK_TX_QUEUE => self.port_send(VsockEvent::TxQueue),
_ => Ok(()),
}
}
pub fn shutdown(&self) -> std::io::Result<()> {
self.port_send(VsockEvent::Shutdown)
}
}
/// Set of `PollFlags` that signifies a readable event.
const fn is_readable(flags: PollFlags) -> bool {
const READABLE: PollFlags = PollFlags::from_bits_truncate(
PollFlags::POLLIN.bits()
| PollFlags::POLLHUP.bits()
| PollFlags::POLLERR.bits()
| PollFlags::POLLPRI.bits(),
);
READABLE.intersects(flags)
}
/// Set of `PollFlags` that signifies a writable event.
const fn is_writable(flags: PollFlags) -> bool {
const WRITABLE: PollFlags = PollFlags::from_bits_truncate(
PollFlags::POLLOUT.bits()
| PollFlags::POLLHUP.bits()
| PollFlags::POLLERR.bits(),
);
WRITABLE.intersects(flags)
}
#[derive(Debug)]
enum RxEvent {
/// Vsock RST packet
Reset(ConnKey),
/// Vsock RESPONSE packet
NewConnection(ConnKey),
/// Vsock CREDIT_UPDATE packet
CreditUpdate(ConnKey),
}
pub struct VsockPoller {
log: Logger,
/// The guest context id
guest_cid: GuestCid,
/// Port mappings we are proxying packets to and from
port_mappings: IdHashMap<VsockPortMapping>,
/// The event port fd.
port_fd: Arc<OwnedFd>,
/// The virtqueues associated with the vsock device
queues: VsockVq,
/// The connection map of guest connected streams
connections: HashMap<ConnKey, VsockProxyConn>,
/// Queue of vsock packets that need to be sent to the guest
rx: VecDeque<RxEvent>,
/// Connections blocked waiting for rx queue descriptors
rx_blocked: Vec<ConnKey>,
}
impl VsockPoller {
/// Create a new `VsockPoller`.
///
/// This poller is responsible for driving virtio-socket connections between
/// the guest VM and host sockets.
pub fn new(
cid: GuestCid,
queues: VsockVq,
log: Logger,
port_mappings: IdHashMap<VsockPortMapping>,
) -> std::io::Result<Self> {
let port_fd = unsafe {
let fd = match libc::port_create() {
-1 => return Err(std::io::Error::last_os_error()),
fd => fd,
};
// Set CLOEXEC on the event port fd
if libc::fcntl(
fd,
libc::F_SETFD,
libc::fcntl(fd, libc::F_GETFD) | libc::FD_CLOEXEC,
) < 0
{
return Err(std::io::Error::last_os_error());
};
fd
};
info!(
&log,
"vsock poller configured with";
"mappings" => ?port_mappings,
);
Ok(Self {
log,
guest_cid: cid,
port_mappings,
port_fd: Arc::new(unsafe { OwnedFd::from_raw_fd(port_fd) }),
queues,
connections: Default::default(),
rx: Default::default(),
rx_blocked: Default::default(),
})
}
/// Get a handle to a `VsockPollerNotify`.
pub fn notify_handle(&self) -> VsockPollerNotify {
VsockPollerNotify { port_fd: Arc::clone(&self.port_fd) }
}
/// Start the event loop.
pub fn run(mut self) -> JoinHandle<()> {
std::thread::Builder::new()
.name("vsock-event-loop".to_string())
.spawn(move || self.handle_events())
.expect("failed to spawn vsock event loop")
}
/// Handle the guest's VIRTIO_VSOCK_OP_REQUEST packet.
fn handle_connection_request(&mut self, key: ConnKey, packet: VsockPacket) {
if self.connections.contains_key(&key) {
// Connection already exists
self.send_conn_rst(key);
return;
}
let Some(mapping) = self.port_mappings.get(&packet.header.dst_port())
else {
// Drop the unknown connection so that it times out in the guest.
warn!(
&self.log,
"dropping connect request to unknown mapping";
"packet" => ?packet,
);
return;
};
match VsockProxyConn::new(mapping.addr()) {
Ok(mut conn) => {
conn.update_peer_credit(&packet.header);
self.connections.insert(key, conn);
self.rx.push_back(RxEvent::NewConnection(key));
}
Err(e) => {
self.send_conn_rst(key);
error!(self.log, "{e}");
}
};
}
/// Handle the guest's VIRTIO_VSOCK_OP_SHUTDOWN packet.
fn handle_shutdown(&mut self, key: ConnKey, flags: VsockPacketFlags) {
if let Entry::Occupied(mut entry) = self.connections.entry(key) {
let conn = entry.get_mut();
// Guest won't receive more data
if flags.contains(VsockPacketFlags::VIRTIO_VSOCK_SHUTDOWN_F_RECEIVE)
{
if let Err(e) = conn.shutdown_guest_read() {
error!(
&self.log,
"cannot transition vsock connection state: {e}";
"conn" => ?conn,
);
entry.remove();
self.send_conn_rst(key);
return;
};
}
// Guest won't send more data
if flags.contains(VsockPacketFlags::VIRTIO_VSOCK_SHUTDOWN_F_SEND) {
if let Err(e) = conn.shutdown_guest_write() {
error!(
&self.log,
"cannot transition vsock connection state: {e}";
"conn" => ?conn,
);
entry.remove();
self.send_conn_rst(key);
return;
};
}
// XXX how do we register this for future cleanup if there is data
// we have not synced locally yet? We need a cleanup loop...
if conn.should_close() {
if !conn.has_buffered_data() {
self.connections.remove(&key);
// virtio spec states:
//
// Clean disconnect is achieved by one or more
// VIRTIO_VSOCK_OP_SHUTDOWN packets that indicate no
// more data will be sent and received, followed by a
// VIRTIO_VSOCK_OP_RST response from the peer.
self.send_conn_rst(key);
}
}
}
}
/// Handle the guest's VIRTIO_VSOCK_OP_RW packet.
fn handle_rw_packet(&mut self, key: ConnKey, packet: VsockPacket) {
if let Entry::Occupied(mut entry) = self.connections.entry(key) {
let conn = entry.get_mut();
// If we have a valid connection, attempt to consume the guest's
// packet.
if let Err(e) = conn.recv_packet(packet) {
error!(
&self.log,
"failed to push vsock packet data into the conn vbuf: {e}";
"conn" => ?conn,
);
entry.remove();
self.send_conn_rst(key);
return;
}
if let Some(interests) = conn.poll_interests() {
let fd = conn.get_fd();
self.associate_fd(key, fd, interests);
}
};
}
/// Handle the guest's tx virtqueue.
fn handle_tx_queue_event(&mut self) {
loop {
let packet = match self.queues.recv_packet().transpose() {
Ok(Some(packet)) => packet,
// No more packets on the guest's tx queue
Ok(None) => break,
Err(e) => {
warn!(&self.log, "dropping invalid vsock packet: {e}");
continue;
}
};
probes::vsock_pkt_tx!(|| &packet.header);
// If the packet is not destined for the host drop it.
if packet.header.dst_cid() != VSOCK_HOST_CID {
warn!(
&self.log,
"droppping vsock packet not destined for the host";
"packet" => ?packet,
);
continue;
}
// If the packet is not coming from our guest drop it.
if packet.header.src_cid() != self.guest_cid.get() {
// Note that we could send a RST here but technically we should
// not know how to address this guest cid as it's not the one
// we assigned to our guest.
warn!(
&self.log,
"droppping vsock packet not arriving from our guest cid";
"packet" => ?packet,
);
continue;
}
let key = ConnKey {
host_port: packet.header.dst_port(),
guest_port: packet.header.src_port(),
};
// We only support stream connections
let Some(VsockSocketType::Stream) = packet.header.socket_type()
else {
self.send_conn_rst(key);
warn!(&self.log,
"received invalid vsock packet type";
"packet" => ?packet,
);
continue;
};
let Some(packet_op) = packet.header.op() else {
warn!(
&self.log,
"received vsock packet with unknown op code";
"packet" => ?packet,
);
return;
};
if let Some(conn) = self.connections.get_mut(&key) {
// Regardless of the vsock operation, we need to record the
// peers credit info
conn.update_peer_credit(&packet.header);
match packet_op {
VsockPacketOp::Reset => {
self.connections.remove(&key);
}
VsockPacketOp::Shutdown => {
self.handle_shutdown(key, packet.header.flags());
}
VsockPacketOp::CreditUpdate => continue,
VsockPacketOp::CreditRequest => {
self.rx.push_back(RxEvent::CreditUpdate(key));
}
VsockPacketOp::ReadWrite => {
self.handle_rw_packet(key, packet);
}
// We are operating on an existing connection either of
// these should not be received
//
// XXX: send a RST, but what about our orignal connection?
op @ (VsockPacketOp::Request | VsockPacketOp::Response) => {
warn!(
&self.log,
"received vsock packet with op code \
{op:?} while operating on an exiting connection"
);
}
}
} else {
match packet_op {
VsockPacketOp::Request => {
self.handle_connection_request(key, packet)
}
VsockPacketOp::Reset => {}
_ => {
warn!(
&self.log,
"received a vsock packet for an unknown connection \
that was not a REQUEST or RST";
"packet" => ?packet,
);
}
}
}
}
}
/// Process the rx virtqueue (host -> guest).
fn handle_rx_queue_event(&mut self) {
// Now that more descriptors have become available for sending vsock
// packets attempt to drain pending packets
self.process_pending_rx();
// Re-register connections that were blocked waiting for rx queue space.
// It would be nice if we had a hint of how many descriptors became
// available but that's not the case today.
for key in std::mem::take(&mut self.rx_blocked).drain(..) {
// It's possible that the guest has sent a RST for this connection
// while we were blocked and we removed our tracked `ConnKey`.
if let Some(conn) = self.connections.get(&key) {
// It's possible that by the time we are ready to send the guest
// data again it has since sent us a SHUTDOWN with the
// `VIRTIO_VSOCK_SHUTDOWN_F_RECEIVE` flag and the connection
// is in the process of shutting down.
if let Some(interests) = conn.poll_interests() {
let fd = conn.get_fd();
self.associate_fd(key, fd, interests);
}
}
}
}
// Attempt to send any queued rx packets destined for the guest.
fn process_pending_rx(&mut self) {
while let Some(permit) = self.queues.try_rx_permit() {
let Some(rx_event) = self.rx.pop_front() else {
break;
};
match rx_event {
RxEvent::Reset(key) => {
let packet = VsockPacket::new_reset(
VsockGuestAddr::from_conn_key(self.guest_cid, key),
);
permit.write(&packet.header, &packet.data);
}
RxEvent::NewConnection(key) => {
let packet = VsockPacket::new_response(
VsockGuestAddr::from_conn_key(self.guest_cid, key),
);
permit.write(&packet.header, &packet.data);
if let Entry::Occupied(mut entry) =
self.connections.entry(key)
{
let conn = entry.get_mut();
if let Err(e) = conn.set_established() {
error!(
&self.log,
"cannot transition vsock connection state: {e}";
"conn" => ?conn,
);
entry.remove();
self.send_conn_rst(key);
continue;
};
if let Some(interests) = conn.poll_interests() {
let fd = conn.get_fd();
self.associate_fd(key, fd, interests);
}
}
}
RxEvent::CreditUpdate(key) => {
if let Some(conn) = self.connections.get_mut(&key) {
let packet = VsockPacket::new_credit_update(
VsockGuestAddr::from_conn_key(self.guest_cid, key),
conn.fwd_cnt(),
);
permit.write(&packet.header, &packet.data);
conn.mark_credit_sent();
}
}
}
}
}
/// Handle a user event. Returns `true` if the event loop should shut down.
fn handle_user_event(&mut self, event: PortEvent) -> bool {
match event.user {
val if val == VsockEvent::TxQueue as usize => {
self.handle_tx_queue_event()
}
val if val == VsockEvent::RxQueue as usize => {
self.handle_rx_queue_event()
}
val if val == VsockEvent::Shutdown as usize => return true,
_ => (),
}
false
}
/// Handle an fd event by flushing data to the underlying socket from the
/// connections [`VsockBuf`], and by reading data from the socket and
/// sending it to the guest as a `VIRTIO_VSOCK_OP_RW` packet.
fn handle_fd_event(&mut self, event: PortEvent, read_buf: &mut [u8]) {
let key = ConnKey::from_portev_user(event.user);
let events = PollFlags::from_bits_retain(event.events as i16);
if is_writable(events) {
self.handle_writable_fd(key);
}
if is_readable(events) {
self.handle_readable_fd(key, read_buf);
}
}
/// When an fd is writable, drain buffered guest data to the host socket.
fn handle_writable_fd(&mut self, key: ConnKey) {
let Some(conn) = self.connections.get_mut(&key) else {
return;
};
loop {
match conn.flush() {
Ok(0) => break,
Ok(nbytes) => {
conn.update_fwd_cnt(nbytes as u32);
if conn.needs_credit_update() {
self.rx.push_back(RxEvent::CreditUpdate(key));
}
}
Err(e) if e.kind() == ErrorKind::WouldBlock => break,
Err(e) => {
error!(&self.log, "error writing to socket: {e}");
break;
}
}
}
// We have finished draining our buffered data to the host, so check if
// we should remove ourselves from the active connections.
if conn.should_close() && !conn.has_buffered_data() {
self.connections.remove(&key);
self.send_conn_rst(key);
return;
}
if let Some(interests) = conn.poll_interests() {
let fd = conn.get_fd();
self.associate_fd(key, fd, interests);
}
}
/// When an fd is readable, read from host socket and send to guest.
fn handle_readable_fd(&mut self, key: ConnKey, read_buf: &mut [u8]) {
let VsockPoller { queues, connections, guest_cid, rx_blocked, .. } =
self;
let Some(conn) = connections.get_mut(&key) else {
return;
};
// The guest is no longer expecting any data
if !conn.guest_can_read() {
return;
}
loop {
let Some(permit) = queues.try_rx_permit() else {
rx_blocked.push(key);
break;
};
let credit = conn.peer_credit();
if credit == 0 {
// TODO: when this happens under sufficient load there's the
// possibility we wake up the event loop repeatedly and we
// should defer associating this fd again until there's enough
// credit. This is similar to the `rx_blocked` queue but
// slightly different.
break;
}
let max_read = read_buf
.len()
// limited by how many bytes the desc chain has
.min(permit.available_data_space())
// limited by how many bytes the guest can handle
.min(credit as usize);
match conn.socket.read(&mut read_buf[..max_read]) {
Ok(0) => {
// TODO the guest is supposed to send us a RST to finalize
// the shutdown. We need to put this on a quiesce queue so
// that we don't leave a half open connection laying around
// in our connection map.
let packet = VsockPacket::new_shutdown(
VsockGuestAddr::from_conn_key(*guest_cid, key),
VsockPacketFlags::VIRTIO_VSOCK_SHUTDOWN_F_SEND
| VsockPacketFlags::VIRTIO_VSOCK_SHUTDOWN_F_RECEIVE,
conn.fwd_cnt(),
);
permit.write(&packet.header, &packet.data);
return;
}
Ok(nbytes) => {
let read_u32: u32 = nbytes
.try_into()
.expect("max_read is <=u32::MAX by min() above");
conn.update_tx_cnt(read_u32);
let VsockPacket { header, data } = VsockPacket::new_rw(
VsockGuestAddr::from_conn_key(*guest_cid, key),
conn.fwd_cnt(),
&read_buf[..nbytes],
);
permit.write(&header, &data);
}
Err(e) if e.kind() == ErrorKind::WouldBlock => break,
Err(e) => {
error!(
&self.log,
"vsock backend socket read failed: {e}";
"key" => ?key,
"conn" => ?conn,
);
connections.remove(&key);
let packet = VsockPacket::new_reset(
VsockGuestAddr::from_conn_key(*guest_cid, key),
);
permit.write(&packet.header, &packet.data);
return;
}
}
}
if let Some(interests) = conn.poll_interests() {
let fd = conn.get_fd();
self.associate_fd(key, fd, interests);
}
}
/// Associate a connections underlying socket fd with our port fd.
fn associate_fd(&mut self, key: ConnKey, fd: RawFd, interests: PollFlags) {
let ret = unsafe {
libc::port_associate(
self.port_fd.as_raw_fd(),
libc::PORT_SOURCE_FD,
fd as usize,
interests.bits() as i32,
key.to_portev_user() as *mut c_void,
)
};
if ret < 0 {
let err = std::io::Error::last_os_error();
if let Some(conn) = self.connections.remove(&key) {
error!(
&self.log,
"vsock port_assocaite failed: {err}";
"key" => ?key,
"conn" => ?conn,
);
self.send_conn_rst(key);
}
}
}
/// Enqueue a RST packet for the provided [`ConnKey`]
fn send_conn_rst(&mut self, key: ConnKey) {
self.rx.push_back(RxEvent::Reset(key));
}
/// This is the vsock event-loop. It's responsible for handling vsock
/// packets to and from the guest.
fn handle_events(&mut self) {
const MAX_EVENTS: u32 = 32;
let mut events = [const { unsafe { std::mem::zeroed::<libc::port_event>() } };
MAX_EVENTS as usize];
let mut read_buf: Box<[u8]> = vec![0u8; 1024 * 64].into();
loop {
let mut nget = 1;
let ret = unsafe {
libc::port_getn(
self.port_fd.as_raw_fd(),
events.as_mut_ptr(),
MAX_EVENTS,
&mut nget,
// TODO currently we are not supplying a timeout because
// there is no other work to do unless we are woken up. In
// the near future we will likely periodically wake up to
// service the shutdown quiesce queue.
std::ptr::null_mut(),
)
};
if ret < 0 {
let err = std::io::Error::last_os_error();
match err.raw_os_error().expect(
"`raw_os_error` is documented to always return `Some` \
+ when obtained via `last_os_error`",
) {
// A signal was caught so process the loop again
libc::EINTR => continue,
libc::EBADF | libc::EBADFD => {
// This means our event loop is effectively no
// longer servicable and the vsock device is useless.
error!(
&self.log,
"vsock port fd is no longer valid: {err}"
);
return;
}
_ => {
error!(&self.log, "vsock port_getn returned: {err}");
continue;
}
}
}
assert!(
nget as usize <= events.len(),
"event port returned what we asked it for"
);
let events = unsafe {
std::slice::from_raw_parts(events.as_ptr(), nget as usize)
};
for event in events {
let event = PortEvent::from_raw(*event);
match event.source {
EventSource::User => {
let should_shutdown = self.handle_user_event(event);
if should_shutdown {
return;
}
}
EventSource::Fd => {
self.handle_fd_event(event, &mut read_buf);
}
_ => {}
};
}
// Process any pending rx events
self.process_pending_rx();
}
}
}
/// The source of a port event.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EventSource {
/// User event i.e. `port_send(3C)`
User,
/// File descriptor event
Fd,
/// Unknown source for the vsock backend
Unknown(u16),
}
impl EventSource {
fn from_raw(source: u16) -> Self {
match source as i32 {
libc::PORT_SOURCE_USER => EventSource::User,
libc::PORT_SOURCE_FD => EventSource::Fd,
_ => EventSource::Unknown(source),
}
}
}
/// A port event retrieved from an event port.
///
/// This represents an event from one of the various event sources (file
/// descriptors, timers, user events, etc.).
#[derive(Debug, Clone)]
struct PortEvent {
/// The events that occurred (source-specific)
events: i32,
/// The source of the event
source: EventSource,
/// The object associated with the event (interpretation depends on source)
#[allow(dead_code)]
object: usize,
/// User-defined data provided during association
user: usize,
}
impl PortEvent {
fn from_raw(event: libc::port_event) -> Self {
PortEvent {
events: event.portev_events,
source: EventSource::from_raw(event.portev_source),
object: event.portev_object,
user: event.portev_user as usize,
}
}
}
impl VsockGuestAddr {
/// Helper function to construct a `[VsockGuestAddr]` from a guest context
/// ID and a `[ConnKey]`.
fn from_conn_key(guest_cid: GuestCid, key: ConnKey) -> Self {
Self { guest_cid, src_port: key.host_port, dst_port: key.guest_port }
}
}
#[cfg(test)]
mod test {
use std::io::{Read, Write};
use std::net::TcpListener;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;
use iddqd::IdHashMap;
use zerocopy::{FromBytes, IntoBytes};
use crate::hw::virtio::testutil::{QueueWriter, TestVirtQueues, VqSize};
use crate::hw::virtio::vsock::{VsockVq, VSOCK_RX_QUEUE, VSOCK_TX_QUEUE};
use crate::vsock::packet::{
VsockPacketFlags, VsockPacketHeader, VsockPacketOp, VsockSocketType,
};
use crate::vsock::proxy::{VsockPortMapping, CONN_TX_BUF_SIZE};
use crate::vsock::{GuestCid, VSOCK_HOST_CID};
use super::VsockPoller;
fn test_logger() -> slog::Logger {
use slog::Drain;
let decorator = slog_term::TermDecorator::new().stderr().build();
let drain = slog_term::FullFormat::new(decorator).build().fuse();
let drain = slog_async::Async::new(drain).build().fuse();
slog::Logger::root(drain, slog::o!("component" => "vsock-test"))
}
const QUEUE_SIZE: u16 = 64;
const PAGE_SIZE: u64 = 0x1000;
/// Bind a TCP listener on an ephemeral port and return it along with an
/// `IdHashMap<VsockPortMapping>` that maps `vsock_port` to the listener's
/// actual address.
fn bind_test_backend(
vsock_port: u32,
) -> (TcpListener, IdHashMap<VsockPortMapping>) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let mut backends = IdHashMap::new();
backends.insert_overwrite(VsockPortMapping::new(vsock_port, addr));
(listener, backends)
}
/// Test harness for vsock poller tests using shared testutil infrastructure.
struct VsockTestHarness {
tvqs: TestVirtQueues,
rx_writer: QueueWriter,
tx_writer: QueueWriter,
}
impl VsockTestHarness {
fn new() -> Self {
let tvqs = TestVirtQueues::new(&[
VqSize::new(QUEUE_SIZE), // RX
VqSize::new(QUEUE_SIZE), // TX
VqSize::new(1), // Event
]);
// RX and TX use separate data regions
let rx_writer = tvqs.writer(VSOCK_RX_QUEUE as usize, 0);
let tx_writer =
tvqs.writer(VSOCK_TX_QUEUE as usize, PAGE_SIZE * 16);
Self { tvqs, rx_writer, tx_writer }
}
fn make_vsock_vq(&self) -> VsockVq {
let queues: Vec<_> =
self.tvqs.queues().iter().map(|q| q.clone()).collect();
let acc = self.tvqs.mem_acc().child(Some("vsock-vq".to_string()));
VsockVq::new(queues, acc)
}
/// Add a writable descriptor to the RX queue and publish it.
fn add_rx_writable(&mut self, len: u32) -> u16 {
let d = self.rx_writer.add_writable(self.tvqs.mem_acc(), len);
self.rx_writer.publish_avail(self.tvqs.mem_acc(), d);
d
}
/// Add a readable descriptor to the TX queue.
fn add_tx_readable(&mut self, data: &[u8]) -> u16 {
self.tx_writer.add_readable(self.tvqs.mem_acc(), data)
}
/// Publish a descriptor on the TX queue.
fn publish_tx(&mut self, head: u16) {
self.tx_writer.publish_avail(self.tvqs.mem_acc(), head);
}
/// Chain two TX descriptors together.
fn chain_tx(&mut self, from: u16, to: u16) {
self.tx_writer.chain(self.tvqs.mem_acc(), from, to);
}
/// Reset TX writer cursors for reuse.
fn reset_tx_cursors(&mut self) {
self.tx_writer.reset_cursors();
}
/// Reset RX writer cursors for reuse.
fn reset_rx_cursors(&mut self) {
self.rx_writer.reset_cursors();
}
/// Read a vsock packet header and data from a used ring entry.
fn read_vsock_packet(
&self,
used_index: u16,
) -> (VsockPacketHeader, Vec<u8>) {
let mem_acc = self.tvqs.mem_acc();
let elem = self.rx_writer.read_used_elem(mem_acc, used_index);
let desc_id = elem.id as u16;
let total_len = elem.len as usize;
// Read the entire buffer (header + data)
let buf =
self.rx_writer.read_desc_data(mem_acc, desc_id, total_len);
// Parse header from the first bytes
let hdr_size = std::mem::size_of::<VsockPacketHeader>();
let (hdr, data) = buf.split_at(hdr_size);
let hdr = VsockPacketHeader::read_from_bytes(hdr)
.expect("buffer should contain valid header");
(hdr, data.to_vec())
}
fn rx_used_idx(&self) -> u16 {
self.rx_writer.used_idx(self.tvqs.mem_acc())
}
fn tx_used_idx(&self) -> u16 {
self.tx_writer.used_idx(self.tvqs.mem_acc())
}
}
/// Helper: serialize a VsockPacketHeader to bytes.
fn hdr_as_bytes(hdr: &VsockPacketHeader) -> &[u8] {
hdr.as_bytes()
}
/// Spin until a condition is met, with a timeout.
fn wait_for_condition<F>(mut f: F, timeout_ms: u64)
where
F: FnMut() -> bool,
{
let start = std::time::Instant::now();
let timeout = Duration::from_millis(timeout_ms);
while !f() {
if start.elapsed() > timeout {
panic!("timed out waiting for condition");
}
std::thread::sleep(Duration::from_millis(1));
}
}
#[test]
fn request_receives_response() {
let vsock_port = 3000;
let guest_port = 1234;
let guest_cid = GuestCid::try_from(50).unwrap();
let (_listener, backends) = bind_test_backend(vsock_port);
let mut harness = VsockTestHarness::new();
let vq = harness.make_vsock_vq();
let log = test_logger();
let poller = VsockPoller::new(guest_cid, vq, log, backends).unwrap();
harness.add_rx_writable(256);
let notify = poller.notify_handle();
let handle = poller.run();
let mut hdr = VsockPacketHeader::new();
hdr.set_src_cid(guest_cid)
.set_dst_cid_raw(VSOCK_HOST_CID)
.set_src_port(guest_port)
.set_dst_port(vsock_port)
.set_len(0)
.set_socket_type(VsockSocketType::Stream)
.set_op(crate::vsock::packet::VsockPacketOp::Request)
.set_buf_alloc(65536)
.set_fwd_cnt(0);
let d_tx = harness.add_tx_readable(hdr_as_bytes(&hdr));
harness.publish_tx(d_tx);
notify.queue_notify(VSOCK_TX_QUEUE).unwrap();