//! The network: a virtio-net device (QEMU's), else Intel's Ethernet on a //! PC's board (`e1000`), under Pinnacle's own stack (`pinnacle-net`), //! interrupt-driven, with its timers on core 0's tick. //! //! A program's TCP connection is a channel: what it sends on its end goes //! out on the connection, what arrives comes to it as messages, and when //! the connection ends its channel closes. The kernel's end of such a //! channel is an endpoint with a sink (`object::Endpoint::sink`), which //! hands what is delivered to it to the stack instead of queueing it. use super::virtio::{self, Buffer, Queue, Transport}; use crate::mm::pages; use crate::object::{Endpoint, Message}; use crate::sync::SpinLock; use alloc::sync::Arc; use alloc::vec::Vec; use core::sync::atomic::{AtomicU64, Ordering}; use pinnacle_net::{Event, IpAddr, SocketId, Stack}; /// VIRTIO_NET_F_MAC: the device's address is in its config space. const F_MAC: u64 = 1 << 5; /// The header virtio-net puts before each frame (with VERSION_1). const HEADER: usize = 12; const RX_BUFFERS: usize = 32; const TX_BUFFERS: usize = 32; /// A buffer: the header and a full Ethernet frame, two to a page. const BUFFER: usize = 2048; struct Virtio { transport: Transport, rx: Queue, tx: Queue, rx_pages: [usize; RX_BUFFERS / 2], tx_pages: [usize; TX_BUFFERS / 2], /// Which tx buffers the device holds. tx_busy: [bool; TX_BUFFERS], } impl Virtio { fn rx_buffer(&self, i: usize) -> usize { self.rx_pages[i / 2] + (i % 2) * BUFFER } fn tx_buffer(&self, i: usize) -> usize { self.tx_pages[i / 2] + (i % 2) * BUFFER } fn send(&mut self, frame: &[u8]) { while let Some((head, _)) = self.tx.take_used() { self.tx_busy[head as usize] = false; } let Some(i) = self.tx_busy.iter().position(|b| !b) else { return; }; let len = frame.len().min(BUFFER - HEADER); let at = self.tx_buffer(i); // SAFETY: a tx buffer the device does not hold. unsafe { core::ptr::write_bytes(at as *mut u8, 0, HEADER); core::ptr::copy_nonoverlapping(frame.as_ptr(), (at + HEADER) as *mut u8, len); } // Descriptor i for buffer i: offered one at a time, lowest free first, // which is the buffer just freed. let head = self.tx.offer(&[Buffer { address: at, len: HEADER + len, device_writes: false, }]); if let Some(head) = head { self.tx_busy[head as usize] = true; } } } struct Net { stack: Stack, device: Device, /// Connections and the kernel's end of each one's channel. sockets: Vec<(SocketId, Arc)>, /// Name lookups and where to answer. lookups: Vec<(u16, Arc)>, /// Listening ports and the kernel's end of each listener's channel, /// on which accepted connections arrive as handles. listeners: Vec<(u16, Arc)>, /// Switched on (Settings switches it off and on again). on: bool, } static NET: SpinLock> = SpinLock::new(None); /// What a program's network channel feeds: a TCP connection, or a UDP /// socket (whose messages, both ways, are the peer's address in four bytes, /// its port in two, big-endian, then the datagram). #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Sink { Tcp(SocketId), Udp(SocketId), /// A listening port: nothing is sent on it; closing it stops listening. Listener(u16), } /// The network device: QEMU's virtio-net, or Intel's Ethernet. enum Device { Virtio(alloc::boxed::Box), Intel(alloc::boxed::Box), } impl Device { fn intid(&self) -> u32 { match self { Device::Virtio(v) => v.transport.intid, Device::Intel(n) => n.intid, } } fn send(&mut self, frame: &[u8]) { match self { Device::Virtio(v) => v.send(frame), Device::Intel(n) => n.send(frame), } } /// Its interrupt acknowledged, and each frame it received handed to /// `each`, its buffer given back. fn receive(&mut self, mut each: impl FnMut(&[u8])) { match self { Device::Virtio(v) => { v.transport.acknowledge(); while let Some((head, len)) = v.rx.take_used() { let at = v.rx_buffer(head as usize); let len = (len as usize).clamp(HEADER, BUFFER); // SAFETY: the device wrote `len` bytes into this rx buffer. each(unsafe { core::slice::from_raw_parts((at + HEADER) as *const u8, len - HEADER) }); v.rx.offer(&[Buffer { address: at, len: BUFFER, device_writes: true, }]); } } Device::Intel(n) => n.receive(each), } } } /// The first virtio-net device, set up: the device and its MAC address. fn virtio_device() -> Option<(Device, [u8; 6])> { let transport = virtio::find(virtio::device::NET).next()?; transport.begin(F_MAC)?; let mac: [u8; 6] = core::array::from_fn(|i| { let word = transport.config_u32(i / 4 * 4); (word >> ((i % 4) * 8)) as u8 }); let rx = Queue::new(transport, 0); let tx = Queue::new(transport, 1); let mut rx_pages = [0; RX_BUFFERS / 2]; for p in &mut rx_pages { *p = pages::alloc(0)?; } let mut tx_pages = [0; TX_BUFFERS / 2]; for p in &mut tx_pages { *p = pages::alloc(0)?; } let mut device = Virtio { transport, rx, tx, rx_pages, tx_pages, tx_busy: [false; TX_BUFFERS], }; for i in 0..RX_BUFFERS { let at = device.rx_buffer(i); device.rx.offer(&[Buffer { address: at, len: BUFFER, device_writes: true, }]); } transport.ready(); Some((Device::Virtio(alloc::boxed::Box::new(device)), mac)) } /// Sets up the network device (virtio-net, else Intel's Ethernet) and /// asks DHCP for an address. Returns its MAC address and what it is. pub fn init() -> Option<([u8; 6], &'static str)> { let (device, mac, what) = match virtio_device() { Some((device, mac)) => (device, mac, "virtio-net"), None => { let (nic, mac) = super::e1000::init()?; let what = if nic.id == 0x10d3 { "Intel 82574L" } else { "Intel Ethernet (e1000e)" }; if !nic.link() { crate::println!("net: {what}: no cable, or no link yet"); } (Device::Intel(alloc::boxed::Box::new(nic)), mac, what) } }; let now = crate::timer::now_ms(); // Its ports and sequence numbers come from the seed: random, or a // restart within one QEMU can reuse the last start's, which its NAT // may still hold as an old connection's. let mut random = [0u8; 8]; crate::drivers::random::fill(&mut random); let mut stack = Stack::new(mac, now ^ crate::board::clock() ^ u64::from_le_bytes(random)); stack.start(now); let mut net = Net { stack, device, sockets: Vec::new(), lookups: Vec::new(), listeners: Vec::new(), on: true, }; flush(&mut net); let intid = net.device.intid(); *NET.lock() = Some(net); // Only now: an interrupt before the driver is in place would find no one. crate::gic::enable_shared(intid); // One may have come already and found no one (an e1000's link change, // by MSI, which sends no other until its causes are read): taken now. interrupt(intid); Some((mac, what)) } /// Sends what the stack has queued and hands its events on. Called with /// the lock held; returns messages to deliver after it is released. /// When the stack's next timer is due (ms since boot; `u64::MAX`: none): /// core 0 sets its timer by it, rather than ticking for it. static DEADLINE: AtomicU64 = AtomicU64::new(u64::MAX); /// When the stack's next timer is due, if one runs. pub fn deadline() -> Option { Some(DEADLINE.load(Ordering::Relaxed)).filter(|&d| d != u64::MAX) } fn flush(net: &mut Net) -> Vec<(Arc, Option)> { let due = net.stack.next_deadline().unwrap_or(u64::MAX); // Core 0 sets its timer when it next switches: make that now, for it // may be asleep with its timer set later, or not at all. if due < DEADLINE.swap(due, Ordering::Relaxed) { crate::gic::send_sgi(0, crate::sched::RESCHEDULE); } while let Some(frame) = net.stack.transmit() { net.device.send(&frame); } let mut out = Vec::new(); while let Some(event) = net.stack.event() { match event { Event::Configured { ip, .. } => { crate::println!("net: address {}.{}.{}.{} from DHCP", ip[0], ip[1], ip[2], ip[3]); } Event::Configured6 { ip, .. } => { crate::println!("net: IPv6 address {} from the router", IpAddr::V6(ip)); } Event::Data { socket, data } => { if let Some((_, end)) = net.sockets.iter().find(|(id, _)| *id == socket) { for chunk in data.chunks(pinnacle_abi::MAX_MESSAGE) { out.push((end.clone(), Some(message(chunk.to_vec())))); } } } Event::Closed { socket, .. } => { // Dropping the kernel's end closes the program's. net.sockets.retain(|(id, _)| *id != socket); } // A program's UDP socket speaks IPv4 (four bytes of address a // message): an IPv6 datagram has no place in it. Event::Datagram { socket, from: IpAddr::V4(from), port, data, } => { if let Some((_, end)) = net.sockets.iter().find(|(id, _)| *id == socket) { let mut bytes = from.to_vec(); bytes.extend_from_slice(&port.to_be_bytes()); bytes.extend_from_slice(&data[..data.len().min(pinnacle_abi::MAX_MESSAGE - 6)]); out.push((end.clone(), Some(message(bytes)))); } } Event::Resolved { query, address } => { if let Some(i) = net.lookups.iter().position(|(q, _)| *q == query) { let (_, end) = net.lookups.remove(i); match address { Some(IpAddr::V4(ip)) => out.push((end, Some(message(ip.to_vec())))), Some(IpAddr::V6(ip)) => out.push((end, Some(message(ip.to_vec())))), None => {} } } } Event::Accepted { listener, socket } => { // The connection as a channel, handed to whoever listens. if let Some((_, end)) = net.listeners.iter().find(|(p, _)| *p == listener) { let (program, kernel) = Endpoint::pair_with_sink(crate::object::Sink::Net(Sink::Tcp(socket))); net.sockets.push((socket, kernel)); out.push(( end.clone(), Some(Message { bytes: Vec::new(), handles: alloc::vec![crate::object::Object::Channel(program)], }), )); } else { net.stack.close(socket, crate::timer::now_ms()); } } Event::Connected { .. } | Event::Datagram { .. } => {} } } out } fn message(bytes: Vec) -> Message { Message { bytes, handles: Vec::new(), } } fn deliver(messages: Vec<(Arc, Option)>) { for (end, message) in messages { if let Some(message) = message { end.send(message); } } } /// Listens on TCP `port`: each connection accepted arrives on the returned /// channel end as a message carrying the connection's channel; closing it /// stops listening. pub fn listen(port: u16) -> Option> { let mut guard = NET.lock(); let net = guard.as_mut().filter(|net| net.on)?; if port == 0 || net.listeners.iter().any(|(p, _)| *p == port) { return None; } net.stack.listen(port); let (program, kernel) = Endpoint::pair_with_sink(crate::object::Sink::Net(Sink::Listener(port))); net.listeners.push((port, kernel)); Some(program) } /// The device's interrupt. False if `intid` is not the network's. pub fn interrupt(intid: u32) -> bool { let mut guard = NET.lock(); let Some(net) = guard.as_mut() else { return false }; if net.device.intid() != intid { return false; } let now = crate::timer::now_ms(); // Switched off, what arrives is dropped; the buffer is offered again. let (on, stack) = (net.on, &mut net.stack); net.device.receive(|frame| { if on { stack.receive(frame, now); } }); let out = flush(net); drop(guard); deliver(out); true } /// The stack's timers, from core 0's tick. pub fn tick() { let mut guard = NET.lock(); let Some(net) = guard.as_mut() else { return }; net.stack.poll(crate::timer::now_ms()); let out = flush(net); drop(guard); deliver(out); } /// A TCP connection to `ip:port`, as the program's end of a channel. pub fn connect(ip: IpAddr, port: u16) -> Option> { let mut guard = NET.lock(); let net = guard.as_mut().filter(|net| net.on)?; let socket = net.stack.connect(ip, port, crate::timer::now_ms()); let (program, kernel) = Endpoint::pair_with_sink(crate::object::Sink::Net(Sink::Tcp(socket))); net.sockets.push((socket, kernel)); let out = flush(net); drop(guard); deliver(out); Some(program) } /// Looks up `name`; the answer (four bytes for IPv4, sixteen for IPv6) arrives on the returned /// channel end, which closes without one if there is none. pub fn resolve(name: &str) -> Option> { let mut guard = NET.lock(); let net = guard.as_mut().filter(|net| net.on)?; let (program, kernel) = Endpoint::pair(); let query = net.stack.resolve(name, crate::timer::now_ms()); net.lookups.push((query, kernel)); let out = flush(net); drop(guard); deliver(out); Some(program) } /// The address, router and name server DHCP gave, once it has. pub fn info() -> Option<([u8; 4], [u8; 4], [u8; 4])> { let guard = NET.lock(); let config = guard.as_ref()?.stack.config()?; Some((config.ip, config.router, config.dns)) } /// The IPv6 address, router and name server, sixteen bytes each (zeros /// for one not known), once a router has given an address. pub fn info6() -> Option<[u8; 48]> { let guard = NET.lock(); let config = guard.as_ref()?.stack.config6()?; let mut out = [0u8; 48]; out[..16].copy_from_slice(&config.ip); out[16..32].copy_from_slice(&config.router.unwrap_or_default()); out[32..].copy_from_slice(&config.dns.unwrap_or_default()); Some(out) } /// A UDP socket on `port` (0: any), as the program's end of a channel, and /// the port it got. pub fn udp_bind(port: u16) -> Option<(Arc, u16)> { let mut guard = NET.lock(); let net = guard.as_mut().filter(|net| net.on)?; let (socket, port) = net.stack.udp_bind(port)?; let (program, kernel) = Endpoint::pair_with_sink(crate::object::Sink::Net(Sink::Udp(socket))); net.sockets.push((socket, kernel)); Some((program, port)) } /// A program sent on its connection or UDP socket. pub fn sink_send(sink: Sink, bytes: &[u8]) { let mut guard = NET.lock(); let Some(net) = guard.as_mut() else { return }; let now = crate::timer::now_ms(); match sink { Sink::Tcp(socket) => net.stack.send(socket, bytes, now), Sink::Udp(socket) if bytes.len() >= 6 => { let to = [bytes[0], bytes[1], bytes[2], bytes[3]]; let port = u16::from_be_bytes([bytes[4], bytes[5]]); net.stack.udp_send_to(socket, to, port, &bytes[6..]); } Sink::Udp(_) | Sink::Listener(_) => {} } let out = flush(net); drop(guard); deliver(out); } /// A program let go of its connection or UDP socket. pub fn sink_close(sink: Sink) { let mut guard = NET.lock(); let Some(net) = guard.as_mut() else { return }; let kept = match sink { Sink::Tcp(socket) => { net.stack.close(socket, crate::timer::now_ms()); None } Sink::Udp(socket) => { net.stack.udp_unbind(socket); let i = net.sockets.iter().position(|(id, _)| *id == socket); i.map(|i| net.sockets.remove(i).1) } Sink::Listener(port) => { net.stack.unlisten(port); let i = net.listeners.iter().position(|(p, _)| *p == port); i.map(|i| net.listeners.remove(i).1) } }; let out = flush(net); drop(guard); // The kernel's end goes outside the lock: dropping it touches the peer. drop(kept); deliver(out); } /// Whether a network device was set up. pub fn present() -> bool { NET.lock().is_some() } /// Where the network is (`pinnacle_abi::net`): no device, switched off, /// on and waiting for DHCP, or online. pub fn state() -> u64 { use pinnacle_abi::net; match NET.lock().as_ref() { None => net::NONE, Some(n) if !n.on => net::OFF, Some(n) if !n.stack.online() => net::CONNECTING, Some(_) => net::ONLINE, } } /// Switches the network off, or on again. Off, the address and every /// connection, socket, listener and lookup go, so the programs holding /// them see their channels close; on, DHCP asks for an address again. pub fn switch(on: bool) { let mut guard = NET.lock(); let Some(net) = guard.as_mut() else { return }; if net.on == on { return; } net.on = on; let mut gone = Vec::new(); if on { net.stack.start(crate::timer::now_ms()); crate::println!("net: switched on"); } else { net.stack.stop(); gone.extend(net.sockets.drain(..).map(|(_, end)| end)); gone.extend(net.lookups.drain(..).map(|(_, end)| end)); gone.extend(net.listeners.drain(..).map(|(_, end)| end)); crate::println!("net: switched off"); } let out = flush(net); drop(guard); // The kernel's ends go outside the lock: dropping one touches its peer. drop(gone); deliver(out); }