Skip to main content

unkernel_rs/
vsock.rs

1//! Host virtio-vsock transport (`wasm_driver_vsock_*`) and blocking stream API for `kwtty`
2//! (`exec`/PTY) and `9P2000.L` mounts.
3
4use std::collections::{HashMap, VecDeque};
5use std::io;
6use std::sync::{Arc, Condvar, Mutex};
7use std::time::{Duration, Instant};
8
9pub const VSOCK_HOST_CID: u64 = 2;
10pub const VSOCK_GUEST_CID: u64 = 3;
11pub const VSOCK_HEADER_SIZE: usize = 44;
12
13const FIRST_HOST_PORT: u32 = 49152;
14const DEFAULT_BUF_ALLOC: u32 = 262_144;
15
16const TYPE_STREAM: u16 = 1;
17
18const OP_REQUEST: u16 = 1;
19const OP_RESPONSE: u16 = 2;
20const OP_RST: u16 = 3;
21const OP_SHUTDOWN: u16 = 4;
22const OP_RW: u16 = 5;
23const OP_CREDIT_UPDATE: u16 = 6;
24const OP_CREDIT_REQUEST: u16 = 7;
25
26const SHUTDOWN_RCV: u32 = 1;
27const SHUTDOWN_SEND: u32 = 2;
28
29#[derive(Debug, Clone, Copy)]
30pub struct VsockHeader {
31    pub src_cid: u64,
32    pub dst_cid: u64,
33    pub src_port: u32,
34    pub dst_port: u32,
35    pub len: u32,
36    pub pkt_type: u16,
37    pub op: u16,
38    pub flags: u32,
39    pub buf_alloc: u32,
40    pub fwd_cnt: u32,
41}
42
43impl VsockHeader {
44    pub fn decode(pkt: &[u8]) -> Option<Self> {
45        if pkt.len() < VSOCK_HEADER_SIZE {
46            return None;
47        }
48        Some(Self {
49            src_cid: u64::from_le_bytes(pkt[0..8].try_into().ok()?),
50            dst_cid: u64::from_le_bytes(pkt[8..16].try_into().ok()?),
51            src_port: u32::from_le_bytes(pkt[16..20].try_into().ok()?),
52            dst_port: u32::from_le_bytes(pkt[20..24].try_into().ok()?),
53            len: u32::from_le_bytes(pkt[24..28].try_into().ok()?),
54            pkt_type: u16::from_le_bytes(pkt[28..30].try_into().ok()?),
55            op: u16::from_le_bytes(pkt[30..32].try_into().ok()?),
56            flags: u32::from_le_bytes(pkt[32..36].try_into().ok()?),
57            buf_alloc: u32::from_le_bytes(pkt[36..40].try_into().ok()?),
58            fwd_cnt: u32::from_le_bytes(pkt[40..44].try_into().ok()?),
59        })
60    }
61
62    pub fn encode(&self, payload: &[u8]) -> Vec<u8> {
63        let mut pkt = Vec::with_capacity(VSOCK_HEADER_SIZE + payload.len());
64        pkt.extend_from_slice(&self.src_cid.to_le_bytes());
65        pkt.extend_from_slice(&self.dst_cid.to_le_bytes());
66        pkt.extend_from_slice(&self.src_port.to_le_bytes());
67        pkt.extend_from_slice(&self.dst_port.to_le_bytes());
68        pkt.extend_from_slice(&(payload.len() as u32).to_le_bytes());
69        pkt.extend_from_slice(&self.pkt_type.to_le_bytes());
70        pkt.extend_from_slice(&self.op.to_le_bytes());
71        pkt.extend_from_slice(&self.flags.to_le_bytes());
72        pkt.extend_from_slice(&self.buf_alloc.to_le_bytes());
73        pkt.extend_from_slice(&self.fwd_cnt.to_le_bytes());
74        pkt.extend_from_slice(payload);
75        pkt
76    }
77}
78
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80enum ConnState {
81    Connecting,
82    Established,
83    Closed,
84}
85
86struct ConnInner {
87    state: ConnState,
88    rx_buf: VecDeque<u8>,
89    rx_cnt: u32,
90    fwd_cnt: u32,
91    sent_fwd: u32,
92    peer_buf_alloc: u32,
93    peer_fwd_cnt: u32,
94    tx_cnt: u32,
95    peer_shut_send: bool,
96    peer_shut_rcv: bool,
97    shut_sent: u32,
98    error: Option<io::ErrorKind>,
99}
100
101struct ConnHandle {
102    local_port: u32,
103    remote_port: u32,
104    inner: Mutex<ConnInner>,
105    cv: Condvar,
106}
107
108impl ConnHandle {
109    fn new(local_port: u32, remote_port: u32, state: ConnState) -> Self {
110        Self {
111            local_port,
112            remote_port,
113            inner: Mutex::new(ConnInner {
114                state,
115                rx_buf: VecDeque::new(),
116                rx_cnt: 0,
117                fwd_cnt: 0,
118                sent_fwd: 0,
119                peer_buf_alloc: 0,
120                peer_fwd_cnt: 0,
121                tx_cnt: 0,
122                peer_shut_send: false,
123                peer_shut_rcv: false,
124                shut_sent: 0,
125                error: None,
126            }),
127            cv: Condvar::new(),
128        }
129    }
130
131    fn peer_credit(c: &ConnInner) -> u32 {
132        c.peer_buf_alloc
133            .saturating_sub(c.tx_cnt.wrapping_sub(c.peer_fwd_cnt))
134    }
135}
136
137/// Callback invoked by `VsockHost` whenever a packet is queued for the guest (raises IRQ_VSOCK).
138type RaiseIrqFn = Arc<dyn Fn() + Send + Sync>;
139type ListenerHandler = Arc<dyn Fn(VsockStream) + Send + Sync>;
140
141struct HostState {
142    guest_cid: u64,
143    max_payload: usize,
144    probed: bool,
145    closed: bool,
146    next_port: u32,
147    to_guest: VecDeque<Vec<u8>>,
148    conns: HashMap<(u32, u32), Arc<ConnHandle>>,
149    listeners: HashMap<u32, ListenerHandler>,
150}
151
152/// Host-side virtio-vsock multiplexer bridged to `wasm_driver_vsock_*`.
153pub struct VsockHost {
154    state: Mutex<HostState>,
155    raise_irq: RaiseIrqFn,
156}
157
158impl VsockHost {
159    pub fn new(raise_irq: RaiseIrqFn) -> Arc<Self> {
160        Arc::new(Self {
161            state: Mutex::new(HostState {
162                guest_cid: VSOCK_GUEST_CID,
163                max_payload: 16384,
164                probed: false,
165                closed: false,
166                next_port: FIRST_HOST_PORT,
167                to_guest: VecDeque::new(),
168                conns: HashMap::new(),
169                listeners: HashMap::new(),
170            }),
171            raise_irq,
172        })
173    }
174
175    /// Called from `wasm_driver_vsock_init(guest_cid, rx_max)`.
176    pub fn driver_init(&self, guest_cid: u32, rx_max: u32) -> i32 {
177        let mut st = self.state.lock().unwrap();
178        st.probed = true;
179        st.guest_cid = guest_cid as u64;
180        if (rx_max as usize) > VSOCK_HEADER_SIZE {
181            st.max_payload = ((rx_max as usize) - VSOCK_HEADER_SIZE).min(65536);
182        }
183        0
184    }
185
186    /// Called from `wasm_driver_vsock_rx_len()`.
187    pub fn driver_rx_len(&self) -> i32 {
188        let st = self.state.lock().unwrap();
189        st.to_guest.front().map(|p| p.len() as i32).unwrap_or(0)
190    }
191
192    /// Called from `wasm_driver_vsock_recv()`.
193    pub fn driver_recv(&self) -> Option<Vec<u8>> {
194        let mut st = self.state.lock().unwrap();
195        st.to_guest.pop_front()
196    }
197
198    /// Called from `wasm_driver_vsock_send(pkt)` when the guest transmits a packet to the host.
199    pub fn driver_send(self: &Arc<Self>, pkt: &[u8]) -> i32 {
200        let Some(h) = VsockHeader::decode(pkt) else {
201            return 0;
202        };
203        if h.dst_cid != VSOCK_HOST_CID || (h.len as usize) != pkt.len() - VSOCK_HEADER_SIZE {
204            return 0;
205        }
206        if h.pkt_type != TYPE_STREAM {
207            self.send_rst(h.src_cid, h.dst_port, h.src_port, h.pkt_type);
208            return 0;
209        }
210
211        let key = (h.dst_port, h.src_port);
212        let existing = { self.state.lock().unwrap().conns.get(&key).cloned() };
213
214        if let Some(conn) = existing {
215            if h.op == OP_REQUEST {
216                self.reset_conn(&conn);
217            } else {
218                self.handle_conn_packet(&conn, h, &pkt[VSOCK_HEADER_SIZE..]);
219            }
220            return 0;
221        }
222
223        if h.op != OP_REQUEST {
224            if h.op != OP_RST {
225                self.send_rst(h.src_cid, h.dst_port, h.src_port, h.pkt_type);
226            }
227            return 0;
228        }
229
230        // Incoming guest connection to a host listener (e.g. port 564 for 9p)
231        let listener = {
232            self.state
233                .lock()
234                .unwrap()
235                .listeners
236                .get(&h.dst_port)
237                .cloned()
238        };
239        let Some(handler) = listener else {
240            self.send_rst(h.src_cid, h.dst_port, h.src_port, h.pkt_type);
241            return 0;
242        };
243
244        let conn = Arc::new(ConnHandle::new(
245            h.dst_port,
246            h.src_port,
247            ConnState::Established,
248        ));
249        {
250            let mut c = conn.inner.lock().unwrap();
251            c.peer_buf_alloc = h.buf_alloc;
252            c.peer_fwd_cnt = h.fwd_cnt;
253        }
254        {
255            let mut st = self.state.lock().unwrap();
256            if st.closed {
257                return 0;
258            }
259            st.conns.insert(key, conn.clone());
260        }
261        self.send_conn_packet(&conn, OP_RESPONSE, 0, &[]);
262
263        let stream = VsockStream {
264            host: self.clone(),
265            conn,
266        };
267        std::thread::Builder::new()
268            .name(format!("vsock-accept-{}", h.dst_port))
269            .spawn(move || handler(stream))
270            .ok();
271        0
272    }
273
274    /// Register a host listener on `port` (e.g. `564` for 9P2000.L).
275    pub fn listen<F>(&self, port: u32, handler: F)
276    where
277        F: Fn(VsockStream) + Send + Sync + 'static,
278    {
279        self.state
280            .lock()
281            .unwrap()
282            .listeners
283            .insert(port, Arc::new(handler));
284    }
285
286    /// Open a host-initiated stream connection to guest `remote_port` (e.g. `1022` for `kwtty`).
287    pub fn connect(
288        self: &Arc<Self>,
289        remote_port: u32,
290        timeout: Duration,
291    ) -> io::Result<VsockStream> {
292        let conn = {
293            let mut st = self.state.lock().unwrap();
294            if st.closed {
295                return Err(io::Error::new(
296                    io::ErrorKind::ConnectionAborted,
297                    "vsock closed",
298                ));
299            }
300            let mut local = st.next_port;
301            while st.listeners.contains_key(&local) || st.conns.contains_key(&(local, remote_port))
302            {
303                local = if local >= u32::MAX - 1 {
304                    FIRST_HOST_PORT
305                } else {
306                    local + 1
307                };
308            }
309            st.next_port = if local >= u32::MAX - 1 {
310                FIRST_HOST_PORT
311            } else {
312                local + 1
313            };
314            let c = Arc::new(ConnHandle::new(local, remote_port, ConnState::Connecting));
315            st.conns.insert((local, remote_port), c.clone());
316            c
317        };
318
319        self.send_conn_packet(&conn, OP_REQUEST, 0, &[]);
320
321        let deadline = Instant::now() + timeout;
322        let mut c = conn.inner.lock().unwrap();
323        while c.state == ConnState::Connecting {
324            let now = Instant::now();
325            if now >= deadline {
326                drop(c);
327                self.reset_conn(&conn);
328                return Err(io::Error::new(
329                    io::ErrorKind::TimedOut,
330                    format!("vsock connect to port {remote_port} timed out"),
331                ));
332            }
333            let (guard, _) = conn.cv.wait_timeout(c, deadline - now).unwrap();
334            c = guard;
335        }
336        if c.state == ConnState::Established {
337            drop(c);
338            Ok(VsockStream {
339                host: self.clone(),
340                conn,
341            })
342        } else {
343            let kind = c.error.unwrap_or(io::ErrorKind::ConnectionRefused);
344            Err(io::Error::new(
345                kind,
346                format!("vsock connect to port {remote_port} refused"),
347            ))
348        }
349    }
350
351    /// Shut down all active vsock connections and wake any blocked readers/writers.
352    pub fn shutdown(&self) {
353        let conns: Vec<Arc<ConnHandle>> = {
354            let mut st = self.state.lock().unwrap();
355            st.closed = true;
356            st.to_guest.clear();
357            st.listeners.clear();
358            st.conns.drain().map(|(_, c)| c).collect()
359        };
360        for conn in conns {
361            let mut c = conn.inner.lock().unwrap();
362            c.state = ConnState::Closed;
363            c.error.get_or_insert(io::ErrorKind::ConnectionAborted);
364            conn.cv.notify_all();
365        }
366    }
367
368    fn queue_to_guest(&self, pkt: Vec<u8>) {
369        {
370            let mut st = self.state.lock().unwrap();
371            if st.closed {
372                return;
373            }
374            st.to_guest.push_back(pkt);
375        }
376        (self.raise_irq)();
377    }
378
379    fn send_rst(&self, dst_cid: u64, src_port: u32, dst_port: u32, pkt_type: u16) {
380        let hdr = VsockHeader {
381            src_cid: VSOCK_HOST_CID,
382            dst_cid,
383            src_port,
384            dst_port,
385            len: 0,
386            pkt_type,
387            op: OP_RST,
388            flags: 0,
389            buf_alloc: 0,
390            fwd_cnt: 0,
391        };
392        self.queue_to_guest(hdr.encode(&[]));
393    }
394
395    fn send_conn_packet(&self, conn: &ConnHandle, op: u16, flags: u32, payload: &[u8]) {
396        let fwd_cnt = {
397            let mut c = conn.inner.lock().unwrap();
398            c.sent_fwd = c.fwd_cnt;
399            c.fwd_cnt
400        };
401        let guest_cid = self.state.lock().unwrap().guest_cid;
402        let hdr = VsockHeader {
403            src_cid: VSOCK_HOST_CID,
404            dst_cid: guest_cid,
405            src_port: conn.local_port,
406            dst_port: conn.remote_port,
407            len: payload.len() as u32,
408            pkt_type: TYPE_STREAM,
409            op,
410            flags,
411            buf_alloc: DEFAULT_BUF_ALLOC,
412            fwd_cnt,
413        };
414        self.queue_to_guest(hdr.encode(payload));
415    }
416
417    fn forget(&self, conn: &ConnHandle) {
418        let mut st = self.state.lock().unwrap();
419        let key = (conn.local_port, conn.remote_port);
420        if let Some(cur) = st.conns.get(&key)
421            && std::ptr::eq(Arc::as_ptr(cur), conn as *const ConnHandle)
422        {
423            st.conns.remove(&key);
424        }
425    }
426
427    fn reset_conn(&self, conn: &ConnHandle) {
428        let was_open = {
429            let mut c = conn.inner.lock().unwrap();
430            if c.state == ConnState::Closed {
431                false
432            } else {
433                c.state = ConnState::Closed;
434                c.error.get_or_insert(io::ErrorKind::ConnectionReset);
435                conn.cv.notify_all();
436                true
437            }
438        };
439        if was_open {
440            self.forget(conn);
441            self.send_conn_packet(conn, OP_RST, 0, &[]);
442        }
443    }
444
445    fn handle_conn_packet(&self, conn: &ConnHandle, h: VsockHeader, payload: &[u8]) {
446        let mut send_credit_update = false;
447        let mut send_rst = false;
448        let mut forget = false;
449
450        {
451            let mut c = conn.inner.lock().unwrap();
452            c.peer_buf_alloc = h.buf_alloc;
453            c.peer_fwd_cnt = h.fwd_cnt;
454
455            match h.op {
456                OP_RESPONSE if c.state == ConnState::Connecting => {
457                    c.state = ConnState::Established;
458                }
459                OP_RW => {
460                    if c.state == ConnState::Established && !payload.is_empty() {
461                        c.rx_cnt = c.rx_cnt.wrapping_add(payload.len() as u32);
462                        c.rx_buf.extend(payload);
463                    }
464                }
465                OP_SHUTDOWN => {
466                    if (h.flags & SHUTDOWN_SEND) != 0 {
467                        c.peer_shut_send = true;
468                    }
469                    if (h.flags & SHUTDOWN_RCV) != 0 {
470                        c.peer_shut_rcv = true;
471                    }
472                    if c.peer_shut_send && c.peer_shut_rcv {
473                        c.state = ConnState::Closed;
474                        send_rst = true;
475                        forget = true;
476                    }
477                }
478                OP_RST => {
479                    if c.state == ConnState::Connecting {
480                        c.error = Some(io::ErrorKind::ConnectionRefused);
481                    } else if !(c.peer_shut_send && (c.shut_sent & SHUTDOWN_SEND) != 0) {
482                        c.error = Some(io::ErrorKind::ConnectionReset);
483                    }
484                    c.state = ConnState::Closed;
485                    forget = true;
486                }
487                OP_CREDIT_REQUEST => {
488                    send_credit_update = true;
489                }
490                OP_CREDIT_UPDATE => {}
491                _ => {
492                    c.state = ConnState::Closed;
493                    c.error = Some(io::ErrorKind::ConnectionReset);
494                    send_rst = true;
495                    forget = true;
496                }
497            }
498            conn.cv.notify_all();
499        }
500
501        if forget {
502            self.forget(conn);
503        }
504        if send_rst {
505            self.send_conn_packet(conn, OP_RST, 0, &[]);
506        } else if send_credit_update {
507            self.send_conn_packet(conn, OP_CREDIT_UPDATE, 0, &[]);
508        }
509    }
510}
511
512/// Blocking bidirectional stream over a guest-host virtio-vsock connection.
513#[derive(Clone)]
514pub struct VsockStream {
515    host: Arc<VsockHost>,
516    conn: Arc<ConnHandle>,
517}
518
519impl VsockStream {
520    /// Read available bytes (blocking until >= 1 byte, EOF `Ok(0)`, or error).
521    pub fn read_chunk(&self, buf: &mut [u8], deadline: Option<Instant>) -> io::Result<usize> {
522        if buf.is_empty() {
523            return Ok(0);
524        }
525        let (n, need_credit_update) = {
526            let mut c = self.conn.inner.lock().unwrap();
527            loop {
528                if !c.rx_buf.is_empty() {
529                    let take = buf.len().min(c.rx_buf.len());
530                    for dst in buf.iter_mut().take(take) {
531                        *dst = c.rx_buf.pop_front().unwrap();
532                    }
533                    c.fwd_cnt = c.fwd_cnt.wrapping_add(take as u32);
534                    let in_flight = c.rx_cnt.wrapping_sub(c.sent_fwd);
535                    let need_update = c.state == ConnState::Established
536                        && DEFAULT_BUF_ALLOC.saturating_sub(in_flight) < DEFAULT_BUF_ALLOC / 2
537                        && c.fwd_cnt != c.sent_fwd;
538                    break (take, need_update);
539                }
540                if c.peer_shut_send {
541                    return Ok(0);
542                }
543                if c.state == ConnState::Closed {
544                    if let Some(kind) = c.error {
545                        return Err(io::Error::new(kind, "vsock connection closed"));
546                    }
547                    return Ok(0);
548                }
549                if let Some(dl) = deadline {
550                    let now = Instant::now();
551                    if now >= dl {
552                        return Err(io::Error::new(
553                            io::ErrorKind::TimedOut,
554                            "vsock read timed out",
555                        ));
556                    }
557                    let (g, _) = self.conn.cv.wait_timeout(c, dl - now).unwrap();
558                    c = g;
559                } else {
560                    c = self.conn.cv.wait(c).unwrap();
561                }
562            }
563        };
564
565        if need_credit_update {
566            self.host
567                .send_conn_packet(&self.conn, OP_CREDIT_UPDATE, 0, &[]);
568        }
569        Ok(n)
570    }
571
572    /// Read exact `buf.len()` bytes.
573    pub fn read_exact_deadline(
574        &self,
575        mut buf: &mut [u8],
576        deadline: Option<Instant>,
577    ) -> io::Result<()> {
578        while !buf.is_empty() {
579            let n = self.read_chunk(buf, deadline)?;
580            if n == 0 {
581                return Err(io::Error::new(
582                    io::ErrorKind::UnexpectedEof,
583                    "vsock unexpected EOF",
584                ));
585            }
586            buf = &mut buf[n..];
587        }
588        Ok(())
589    }
590
591    /// Write all of `data` respecting peer credit flow control and `max_payload`.
592    pub fn write_all_deadline(&self, mut data: &[u8], deadline: Option<Instant>) -> io::Result<()> {
593        let max_payload = self.host.state.lock().unwrap().max_payload;
594        while !data.is_empty() {
595            let chunk_len = {
596                let mut c = self.conn.inner.lock().unwrap();
597                let mut asked_credit = false;
598                loop {
599                    if c.state == ConnState::Closed {
600                        return Err(io::Error::new(
601                            c.error.unwrap_or(io::ErrorKind::BrokenPipe),
602                            "vsock closed",
603                        ));
604                    }
605                    if c.peer_shut_rcv {
606                        return Err(io::Error::new(
607                            io::ErrorKind::BrokenPipe,
608                            "guest shut down receive side",
609                        ));
610                    }
611                    let credit = ConnHandle::peer_credit(&c) as usize;
612                    if credit > 0 {
613                        let n = credit.min(max_payload).min(data.len());
614                        c.tx_cnt = c.tx_cnt.wrapping_add(n as u32);
615                        break n;
616                    }
617                    if !asked_credit {
618                        asked_credit = true;
619                        drop(c);
620                        self.host
621                            .send_conn_packet(&self.conn, OP_CREDIT_REQUEST, 0, &[]);
622                        c = self.conn.inner.lock().unwrap();
623                        continue;
624                    }
625                    let wait = if let Some(dl) = deadline {
626                        let now = Instant::now();
627                        if now >= dl {
628                            return Err(io::Error::new(
629                                io::ErrorKind::TimedOut,
630                                "vsock write timed out",
631                            ));
632                        }
633                        (dl - now).min(Duration::from_millis(200))
634                    } else {
635                        Duration::from_millis(200)
636                    };
637                    let (g, res) = self.conn.cv.wait_timeout(c, wait).unwrap();
638                    c = g;
639                    if res.timed_out() {
640                        asked_credit = false;
641                    }
642                }
643            };
644            self.host
645                .send_conn_packet(&self.conn, OP_RW, 0, &data[..chunk_len]);
646            data = &data[chunk_len..];
647        }
648        Ok(())
649    }
650
651    pub fn shutdown_write(&self) {
652        let should_send = {
653            let mut c = self.conn.inner.lock().unwrap();
654            if c.state != ConnState::Established || (c.shut_sent & SHUTDOWN_SEND) != 0 {
655                None
656            } else {
657                c.shut_sent |= SHUTDOWN_SEND;
658                Some(c.shut_sent)
659            }
660        };
661        if let Some(flags) = should_send {
662            self.host
663                .send_conn_packet(&self.conn, OP_SHUTDOWN, flags, &[]);
664        }
665    }
666
667    pub fn close(&self) {
668        let send_shut = {
669            let mut c = self.conn.inner.lock().unwrap();
670            if c.state == ConnState::Closed {
671                false
672            } else {
673                c.shut_sent = SHUTDOWN_RCV | SHUTDOWN_SEND;
674                c.state = ConnState::Closed;
675                self.conn.cv.notify_all();
676                true
677            }
678        };
679        if send_shut {
680            self.host.forget(&self.conn);
681            self.host
682                .send_conn_packet(&self.conn, OP_SHUTDOWN, SHUTDOWN_RCV | SHUTDOWN_SEND, &[]);
683        }
684    }
685
686    pub fn reset(&self) {
687        self.host.reset_conn(&self.conn);
688    }
689}