Skip to main content

strat9_kernel/syscall/
net.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! Network syscall handlers.
24//!
25//! Two data planes coexist:
26//!
27//! * **legacy copy path** : `SYS_NET_SEND` / `SYS_NET_RECV` copy one frame
28//!   through a 2 KiB stack buffer.  Kept for compatibility and for bring-up;
29//! * **shared queue path** : `SYS_NET_QUEUE_MAP` maps the `NetQueue` region
30//!   into the networking strate, which then drives the descriptor rings
31//!   directly (`SYS_NET_KICK` / `SYS_NET_EVENT_WAIT`).
32//!
33//! Every entry point is capability-gated: the caller must hold a `Nic`
34//! capability obtained with `SYS_NET_OPEN`.  Raw packet access is therefore
35//! no longer ambient authority.
36
37use super::error::SyscallError;
38use crate::{
39    capability::{get_capability_manager, CapId, CapPermissions, ResourceType},
40    hardware::nic::{self, hotplug, net_queue::NetQueue},
41    memory::{
42        address_space::{VmaFlags, VmaPageSize, VmaType},
43        UserSliceRead, UserSliceWrite,
44    },
45    process::current_task_clone,
46    silo::{self, StrateFamily},
47};
48use core::sync::atomic::Ordering;
49use strat9_abi::net::{
50    event, features, link_flags, NetEvent, NetFrame, NetFrameDesc, NetLinkInfo, NetQueueInfo,
51    NetQueueMap, NetStats, NET_FRAME_SIZE, NET_POOL_SLOTS, NET_RING_SLOTS,
52};
53
54/// Maximum frame accepted on the legacy path (Ethernet frame + VLAN).
55const MAX_FRAME: usize = NET_FRAME_SIZE;
56/// Minimum Ethernet frame (two MAC addresses + EtherType).
57const MIN_FRAME: usize = 14;
58/// Maximum number of frames in one batch syscall.
59const MAX_BATCH: usize = 32;
60
61// ---------------------------------------------------------------------------
62// Capability helpers
63// ---------------------------------------------------------------------------
64
65fn nic_capability(handle: u64, required: CapPermissions) -> Result<usize, SyscallError> {
66    silo::enforce_cap_for_current_task(handle)?;
67    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
68    // SAFETY: the table is internally synchronized; a shared reference is
69    // sound across threads.
70    let caps = unsafe { &*task.process.capabilities.get() };
71    let cap = caps
72        .get_with_permissions(CapId::from_raw(handle), required)
73        .ok_or(SyscallError::PermissionDenied)?;
74    if cap.resource_type != ResourceType::Nic {
75        return Err(SyscallError::BadHandle);
76    }
77    Ok(cap.resource)
78}
79
80/// Check for a `Nic` capability without resolving the device.
81///
82/// Hotplug events must remain readable after the device has been removed
83/// from the registry, so this variant does not call `get_device_by_resource`.
84fn nic_cap_present(required: CapPermissions) -> Result<(), SyscallError> {
85    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
86    // SAFETY: the table is internally synchronized.
87    let caps = unsafe { &*task.process.capabilities.get() };
88    caps.find_by_type_with_permissions(ResourceType::Nic, required)
89        .map(|_| ())
90        .ok_or(SyscallError::PermissionDenied)
91}
92
93/// Resolve the default NIC through the caller's `Nic` capability.
94fn default_nic(
95    required: CapPermissions,
96) -> Result<alloc::sync::Arc<dyn nic::NetworkDevice>, SyscallError> {
97    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
98    // SAFETY: the table is internally synchronized.
99    let caps = unsafe { &*task.process.capabilities.get() };
100    let cap = caps
101        .find_by_type_with_permissions(ResourceType::Nic, required)
102        .ok_or(SyscallError::PermissionDenied)?;
103    nic::get_device_by_resource(cap.resource).ok_or(SyscallError::NotFound)
104}
105
106fn nic_from_handle(
107    handle: u64,
108    required: CapPermissions,
109) -> Result<alloc::sync::Arc<dyn nic::NetworkDevice>, SyscallError> {
110    let resource = nic_capability(handle, required)?;
111    nic::get_device_by_resource(resource).ok_or(SyscallError::NotFound)
112}
113
114fn queue_from_handle(handle: u64, qid: u16) -> Result<alloc::sync::Arc<NetQueue>, SyscallError> {
115    let resource = nic_capability(
116        handle,
117        CapPermissions {
118            read: true,
119            write: true,
120            execute: false,
121            grant: false,
122            revoke: false,
123        },
124    )?;
125    let guard = nic::data_plane().lock();
126    guard
127        .as_ref()
128        .and_then(|dp| dp.queue_for(resource as u64, qid))
129        .ok_or(SyscallError::BadHandle)
130}
131
132// ---------------------------------------------------------------------------
133// Open / register / info
134// ---------------------------------------------------------------------------
135
136/// `SYS_NET_OPEN`: obtain a `Nic` capability for the default device.
137///
138/// Only `NET`, `DRV` and `SYS` silos may open the raw device.  The returned
139/// handle is inserted into the caller's capability table; subsequent legacy
140/// calls resolve it automatically.
141pub fn sys_net_open() -> Result<u64, SyscallError> {
142    let family = silo::current_task_family().ok_or(SyscallError::PermissionDenied)?;
143    if !matches!(
144        family,
145        StrateFamily::NET | StrateFamily::DRV | StrateFamily::SYS
146    ) {
147        return Err(SyscallError::PermissionDenied);
148    }
149
150    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
151    // SAFETY: the table is internally synchronized.
152    let caps = unsafe { &*task.process.capabilities.get() };
153
154    // Idempotent: return the existing capability if already opened.
155    let required = CapPermissions::read_write();
156    if let Some(existing) = caps.find_by_type_with_permissions(ResourceType::Nic, required) {
157        return Ok(existing.id.as_u64());
158    }
159
160    let (_dev, resource) = nic::default_device_with_id().ok_or(SyscallError::Again)?;
161    let cap = get_capability_manager().create_capability(
162        ResourceType::Nic,
163        resource,
164        CapPermissions {
165            read: true,
166            write: true,
167            execute: false,
168            grant: false,
169            revoke: true,
170        },
171    );
172    let id = caps.insert(cap);
173    Ok(id.as_u64())
174}
175
176/// `SYS_NET_REGISTER`: register the calling task as the networking silo.
177pub fn sys_net_register() -> Result<u64, SyscallError> {
178    let _dev = default_nic(CapPermissions::read_write())?;
179    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
180    nic::register_strate_net_tid(task.id.as_u64());
181    log::info!(
182        "[net] networking strate registered (tid={})",
183        task.id.as_u64()
184    );
185    Ok(0)
186}
187
188/// `SYS_NET_INFO`: query interface information.
189///
190/// `info_type`:
191/// * 0 : MAC address (6 bytes)
192/// * 1 : `NetLinkInfo`
193/// * 2 : MTU (`u32`)
194/// * 3 : link up (`u8`)
195/// * 4 : queue count (`u32`)
196pub fn sys_net_info(info_type: u64, buf_ptr: u64) -> Result<u64, SyscallError> {
197    let dev = default_nic(CapPermissions {
198        read: true,
199        write: false,
200        execute: false,
201        grant: false,
202        revoke: false,
203    })?;
204
205    match info_type {
206        0 => {
207            let mac = dev.mac_address();
208            let user = UserSliceWrite::new(buf_ptr, mac.len())?;
209            user.copy_from(&mac);
210            Ok(mac.len() as u64)
211        }
212        1 => {
213            let queue = {
214                let guard = nic::data_plane().lock();
215                guard.as_ref().and_then(|dp| dp.clone_queue(0))
216            };
217            let epoch = queue
218                .as_ref()
219                .map(|q| q.header().epoch.load(Ordering::Acquire))
220                .unwrap_or(1);
221            let mtu = queue
222                .as_ref()
223                .map(|q| q.header().mtu.load(Ordering::Acquire))
224                .unwrap_or(1500);
225            let info = NetLinkInfo {
226                mac: dev.mac_address(),
227                _pad: 0,
228                mtu,
229                flags: if dev.link_up() {
230                    link_flags::UP | link_flags::CARRIER | link_flags::FULL_DUPLEX
231                } else {
232                    0
233                },
234                speed_mbps: 0,
235                epoch,
236            };
237            let user = UserSliceWrite::new(buf_ptr, core::mem::size_of::<NetLinkInfo>())?;
238            let bytes = unsafe {
239                core::slice::from_raw_parts(
240                    &info as *const NetLinkInfo as *const u8,
241                    core::mem::size_of::<NetLinkInfo>(),
242                )
243            };
244            user.copy_from(bytes);
245            Ok(core::mem::size_of::<NetLinkInfo>() as u64)
246        }
247        2 => {
248            let mtu: u32 = dev.mtu() as u32;
249            let user = UserSliceWrite::new(buf_ptr, 4)?;
250            user.copy_from(&mtu.to_le_bytes());
251            Ok(4)
252        }
253        3 => {
254            let up = if dev.link_up() { 1u8 } else { 0u8 };
255            let user = UserSliceWrite::new(buf_ptr, 1)?;
256            user.copy_from(&[up]);
257            Ok(1)
258        }
259        4 => {
260            let count = nic::default_queue_count() as u32;
261            let user = UserSliceWrite::new(buf_ptr, 4)?;
262            user.copy_from(&count.to_le_bytes());
263            Ok(4)
264        }
265        _ => Err(SyscallError::InvalidArgument),
266    }
267}
268
269// ---------------------------------------------------------------------------
270// Legacy one-frame path
271// ---------------------------------------------------------------------------
272
273fn validate_frame(len: usize) -> Result<(), SyscallError> {
274    if !(MIN_FRAME..=MAX_FRAME).contains(&len) {
275        return Err(SyscallError::MessageSize);
276    }
277    Ok(())
278}
279
280/// `SYS_NET_RECV`: receive one raw Ethernet frame.
281pub fn sys_net_recv(buf_ptr: u64, buf_len: u64) -> Result<u64, SyscallError> {
282    let _cap = default_nic(CapPermissions {
283        read: true,
284        write: false,
285        execute: false,
286        grant: false,
287        revoke: false,
288    })?;
289
290    let requested = usize::try_from(buf_len).map_err(|_| SyscallError::InvalidArgument)?;
291    if requested < MIN_FRAME {
292        return Err(SyscallError::InvalidArgument);
293    }
294    let requested = requested.min(MAX_FRAME);
295
296    let mut kbuf = [0u8; MAX_FRAME];
297    let n = {
298        // Prefer the N2 rings (IRQ-filled). The IRQ path RSS-distributes
299        // frames across every queue of the device, but a legacy consumer has
300        // no queue-to-thread mapping: it must drain *all* queues. Popping only
301        // queue 0 silently stranded every frame whose hash landed on another
302        // queue (observed: ARP replies and TCP SYN-ACK paths lost, so DHCP and
303        // broadcast worked while unicast services never answered).
304        let device_resource = nic::default_device_with_id().map(|(_, resource)| resource as u64);
305        let mut from_ring = None;
306        {
307            let guard = nic::data_plane().lock();
308            if let Some(dp) = guard.as_ref() {
309                if let Some(resource) = device_resource {
310                    let queues = dp.queue_count_for(resource).max(1);
311                    for qid in 0..queues {
312                        match dp.pop_rx_for(resource, qid, &mut kbuf[..requested]) {
313                            Ok(Some(n)) => {
314                                from_ring = Some(n);
315                                break;
316                            }
317                            Ok(None) => {}
318                            Err(nic::data_plane::RxError::InvalidQueue) => break,
319                            Err(error) => return Err(error.into()),
320                        }
321                    }
322                }
323            }
324        }
325        match from_ring {
326            Some(n) => n,
327            None => {
328                let dev = nic::get_default_device().ok_or(SyscallError::Again)?;
329                match dev.receive(&mut kbuf[..requested]) {
330                    Ok(n) => n,
331                    Err(nic::NetError::NoPacket) => return Err(SyscallError::Again),
332                    Err(nic::NetError::LinkDown) => return Err(SyscallError::IoError),
333                    Err(_) => return Err(SyscallError::IoError),
334                }
335            }
336        }
337    };
338
339    if n == 0 || n > requested {
340        return Err(SyscallError::IoError);
341    }
342    let user = UserSliceWrite::new(buf_ptr, n)?;
343    user.copy_from(&kbuf[..n]);
344    Ok(n as u64)
345}
346
347/// `SYS_NET_SEND`: transmit one raw Ethernet frame.
348pub fn sys_net_send(buf_ptr: u64, buf_len: u64) -> Result<u64, SyscallError> {
349    let _cap = default_nic(CapPermissions {
350        read: false,
351        write: true,
352        execute: false,
353        grant: false,
354        revoke: false,
355    })?;
356
357    let len = usize::try_from(buf_len).map_err(|_| SyscallError::InvalidArgument)?;
358    validate_frame(len)?;
359
360    let user = UserSliceRead::new(buf_ptr, len)?;
361    let mut kbuf = [0u8; MAX_FRAME];
362    let copied = user.copy_to(&mut kbuf[..len]);
363    if copied != len {
364        return Err(SyscallError::Fault);
365    }
366
367    let mut present = false;
368    let pushed = {
369        let guard = nic::data_plane().lock();
370        match guard.as_ref() {
371            Some(dp) => {
372                present = true;
373                dp.push_tx(0, &kbuf[..len]).is_ok()
374            }
375            None => false,
376        }
377    };
378
379    if present {
380        if !pushed {
381            // Backpressure: do not bypass the shared ring, or packets would
382            // be reordered relative to frames already queued.
383            return Err(SyscallError::Again);
384        }
385        // Keep the TX path independent from RX interrupts.  If the device
386        // queue is full, the frame stays in the shared TX ring and will be
387        // flushed by the next kick or IRQ.
388        nic::flush_tx(0);
389        return Ok(len as u64);
390    }
391
392    // No data plane: fall back to the direct driver path.
393    let dev = nic::get_default_device().ok_or(SyscallError::Again)?;
394    dev.transmit(&kbuf[..len])
395        .map_err(|_| SyscallError::Again)?;
396    Ok(len as u64)
397}
398
399// ---------------------------------------------------------------------------
400// Shared-queue path
401// ---------------------------------------------------------------------------
402
403/// `SYS_NET_QUEUE_MAP`: map a `NetQueue` region into the caller.
404pub fn sys_net_queue_map(dev: u64, qid: u64, out_ptr: u64) -> Result<u64, SyscallError> {
405    let resource = nic_capability(dev, CapPermissions::read_write())?;
406    if qid > u16::MAX as u64 {
407        return Err(SyscallError::InvalidArgument);
408    }
409    let queue = {
410        let guard = nic::data_plane().lock();
411        guard
412            .as_ref()
413            .and_then(|dp| dp.queue_for(resource as u64, qid as u16))
414            .ok_or(SyscallError::BadHandle)?
415    };
416
417    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
418    let ring = queue.region();
419    if !queue.try_map(task.id.as_u64()) {
420        return Err(SyscallError::AlreadyExists);
421    }
422    let result = (|| -> Result<u64, SyscallError> {
423        let frames = ring.frame_phys_addrs();
424        let mapping_caps = ring.mapping_cap_ids().to_vec();
425        let pages = ring.page_count();
426        let size = pages
427            .checked_mul(4096)
428            .ok_or(SyscallError::InvalidArgument)? as u64;
429
430        let addr_space = task.process.address_space_arc();
431        let base = addr_space
432            .find_free_vma_range(crate::kaslr::mmap_base(), pages, VmaPageSize::Small)
433            .ok_or(SyscallError::OutOfMemory)?;
434
435        addr_space
436            .map_shared_frames_with_cap_ids(
437                base,
438                &frames,
439                Some(&mapping_caps),
440                VmaFlags {
441                    readable: true,
442                    writable: true,
443                    executable: false,
444                    user_accessible: true,
445                },
446                VmaType::Anonymous,
447            )
448            .map_err(|_| SyscallError::OutOfMemory)?;
449
450        let map = NetQueueMap {
451            base,
452            len: size,
453            qid: qid as u16,
454            frame_size: NET_FRAME_SIZE as u16,
455            slots: NET_RING_SLOTS as u16,
456            flags: 0,
457        };
458        let user = UserSliceWrite::new(out_ptr, core::mem::size_of::<NetQueueMap>())?;
459        let bytes = unsafe {
460            core::slice::from_raw_parts(
461                &map as *const NetQueueMap as *const u8,
462                core::mem::size_of::<NetQueueMap>(),
463            )
464        };
465        user.copy_from(bytes);
466        queue.set_mapped_base(base);
467        Ok(size)
468    })();
469    if result.is_err() {
470        queue.unmap_reservation();
471    }
472    result
473}
474
475/// `SYS_NET_QUEUE_UNMAP`: unmap a shared queue region.
476///
477/// Called by a restarted strate before re-mapping.  The queue reservation is
478/// released only after the PTEs are removed.
479pub fn sys_net_queue_unmap(dev: u64, qid: u64) -> Result<u64, SyscallError> {
480    let resource = nic_capability(dev, CapPermissions::read_write())?;
481    if qid > u16::MAX as u64 {
482        return Err(SyscallError::InvalidArgument);
483    }
484    let queue = {
485        let guard = nic::data_plane().lock();
486        guard
487            .as_ref()
488            .and_then(|dp| dp.queue_for(resource as u64, qid as u16))
489            .ok_or(SyscallError::BadHandle)?
490    };
491    let base = queue.take_mapped_base();
492    if base == 0 {
493        return Ok(0);
494    }
495    let pages = queue.region().page_count();
496    let size = (pages as u64)
497        .checked_mul(4096)
498        .ok_or(SyscallError::InvalidArgument)?;
499    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
500    task.process
501        .address_space_arc()
502        .unmap_range(base, size)
503        .map_err(|_| SyscallError::IoError)?;
504    queue.unmap_reservation();
505    Ok(0)
506}
507
508/// `SYS_NET_KICK`: drain the shared TX ring to the device.
509pub fn sys_net_kick(dev: u64, qid: u64) -> Result<u64, SyscallError> {
510    let resource = nic_capability(
511        dev,
512        CapPermissions {
513            read: false,
514            write: true,
515            execute: false,
516            grant: false,
517            revoke: false,
518        },
519    )?;
520    if qid > u16::MAX as u64 {
521        return Err(SyscallError::InvalidArgument);
522    }
523    Ok(nic::flush_tx_for(resource as u64, qid as u16) as u64)
524}
525
526/// `SYS_NET_IRQ_BIND`: route queue RX events to an IPC port.
527pub fn sys_net_irq_bind(dev: u64, qid: u64, port: u64) -> Result<u64, SyscallError> {
528    if qid > u16::MAX as u64 {
529        return Err(SyscallError::InvalidArgument);
530    }
531    let queue = queue_from_handle(dev, qid as u16)?;
532    queue.port.store(port, Ordering::Release);
533    // The actual IRQ registration is performed by the device manager when
534    // MSI-X vectors are available; storing the port is enough for the poll
535    // path, which notifies the queue event.
536    Ok(0)
537}
538
539/// `SYS_NET_TX_PUBLISH`: publish a TX descriptor and kick the device.
540pub fn sys_net_tx_publish(dev: u64, qid: u64) -> Result<u64, SyscallError> {
541    sys_net_kick(dev, qid)
542}
543
544/// `SYS_NET_LINK`: query link state and MTU.
545pub fn sys_net_link(dev: u64, out_ptr: u64) -> Result<u64, SyscallError> {
546    let device = nic_from_handle(
547        dev,
548        CapPermissions {
549            read: true,
550            write: false,
551            execute: false,
552            grant: false,
553            revoke: false,
554        },
555    )?;
556    let queue = {
557        let guard = nic::data_plane().lock();
558        guard.as_ref().and_then(|dp| dp.clone_queue(0))
559    };
560    let epoch = queue
561        .as_ref()
562        .map(|q| q.header().epoch.load(Ordering::Acquire))
563        .unwrap_or(1);
564    let mtu = queue
565        .as_ref()
566        .map(|q| q.header().mtu.load(Ordering::Acquire))
567        .unwrap_or_else(|| device.mtu() as u32);
568    let info = NetLinkInfo {
569        mac: device.mac_address(),
570        _pad: 0,
571        mtu,
572        flags: if device.link_up() {
573            link_flags::UP | link_flags::CARRIER | link_flags::FULL_DUPLEX
574        } else {
575            0
576        },
577        speed_mbps: 0,
578        epoch,
579    };
580    let user = UserSliceWrite::new(out_ptr, core::mem::size_of::<NetLinkInfo>())?;
581    let bytes = unsafe {
582        core::slice::from_raw_parts(
583            &info as *const NetLinkInfo as *const u8,
584            core::mem::size_of::<NetLinkInfo>(),
585        )
586    };
587    user.copy_from(bytes);
588    Ok(core::mem::size_of::<NetLinkInfo>() as u64)
589}
590
591/// `SYS_NET_RX_BATCH`: receive up to `count` frames.
592///
593/// The `frames` array is an array of `NetFrame` entries.  Each entry points
594/// to a user buffer that receives one frame.  This is a compatibility
595/// batching path; the shared queue remains the zero-copy path.
596pub fn sys_net_rx_batch(dev: u64, frames_ptr: u64, count: u64) -> Result<u64, SyscallError> {
597    let _resource = nic_capability(
598        dev,
599        CapPermissions {
600            read: true,
601            write: false,
602            execute: false,
603            grant: false,
604            revoke: false,
605        },
606    )?;
607    let count = (count as usize).min(MAX_BATCH);
608    if count == 0 {
609        return Ok(0);
610    }
611    let bytes = count
612        .checked_mul(core::mem::size_of::<NetFrame>())
613        .ok_or(SyscallError::InvalidArgument)?;
614    let user = UserSliceRead::new(frames_ptr, bytes)?;
615    let mut raw = alloc::vec![0u8; bytes];
616    user.copy_to(&mut raw);
617
618    let mut done = 0usize;
619    for index in 0..count {
620        let offset = index * core::mem::size_of::<NetFrame>();
621        let frame = unsafe { core::ptr::read_unaligned(raw[offset..].as_ptr() as *const NetFrame) };
622        if frame.len as usize > MAX_FRAME {
623            return Err(SyscallError::MessageSize);
624        }
625        let mut kbuf = [0u8; MAX_FRAME];
626        let n = {
627            let guard = nic::data_plane().lock();
628            match guard.as_ref() {
629                Some(dp) => match dp.pop_rx(0, &mut kbuf[..frame.len as usize]) {
630                    Ok(Some(n)) => n,
631                    Ok(None) => break,
632                    Err(_) => break,
633                },
634                None => break,
635            }
636        };
637        let out = UserSliceWrite::new(frame.addr, n)?;
638        out.copy_from(&kbuf[..n]);
639        done += 1;
640    }
641    Ok(done as u64)
642}
643
644/// `SYS_NET_TX_BATCH`: transmit up to `count` frames, then kick once.
645pub fn sys_net_tx_batch(dev: u64, frames_ptr: u64, count: u64) -> Result<u64, SyscallError> {
646    let _resource = nic_capability(dev, CapPermissions::read_write())?;
647    let count = (count as usize).min(MAX_BATCH);
648    if count == 0 {
649        return Ok(0);
650    }
651    let bytes = count
652        .checked_mul(core::mem::size_of::<NetFrame>())
653        .ok_or(SyscallError::InvalidArgument)?;
654    let user = UserSliceRead::new(frames_ptr, bytes)?;
655    let mut raw = alloc::vec![0u8; bytes];
656    user.copy_to(&mut raw);
657
658    let mut done = 0usize;
659    for index in 0..count {
660        let offset = index * core::mem::size_of::<NetFrame>();
661        let frame = unsafe { core::ptr::read_unaligned(raw[offset..].as_ptr() as *const NetFrame) };
662        let len = frame.len as usize;
663        if !(MIN_FRAME..=MAX_FRAME).contains(&len) {
664            return Err(SyscallError::MessageSize);
665        }
666        let src = UserSliceRead::new(frame.addr, len)?;
667        let mut kbuf = [0u8; MAX_FRAME];
668        if src.copy_to(&mut kbuf[..len]) != len {
669            return Err(SyscallError::Fault);
670        }
671        let ok = {
672            let guard = nic::data_plane().lock();
673            match guard.as_ref() {
674                Some(dp) => dp.push_tx(0, &kbuf[..len]).is_ok(),
675                None => false,
676            }
677        };
678        if !ok {
679            break;
680        }
681        done += 1;
682    }
683    if done > 0 {
684        nic::flush_tx(0);
685    }
686    Ok(done as u64)
687}
688
689/// `SYS_NET_QUEUE_INFO`: query features, epoch and counters.
690pub fn sys_net_queue_info(dev: u64, qid: u64, out_ptr: u64) -> Result<u64, SyscallError> {
691    if qid > u16::MAX as u64 {
692        return Err(SyscallError::InvalidArgument);
693    }
694    let queue = queue_from_handle(dev, qid as u16)?;
695    let header = queue.header();
696    let info = NetQueueInfo {
697        features: header.features.load(Ordering::Acquire),
698        qid: queue.qid,
699        slots: NET_RING_SLOTS as u16,
700        frame_size: NET_FRAME_SIZE as u16,
701        _pad0: 0,
702        epoch: header.epoch.load(Ordering::Acquire),
703        mtu: header.mtu.load(Ordering::Acquire),
704        stats: NetStats {
705            rx_packets: 0,
706            rx_bytes: 0,
707            rx_dropped: header.rx_dropped.load(Ordering::Relaxed),
708            tx_packets: 0,
709            tx_bytes: 0,
710            tx_dropped: header.tx_dropped.load(Ordering::Relaxed),
711            irqs: header.irq_count.load(Ordering::Relaxed),
712            polls: header.poll_count.load(Ordering::Relaxed),
713        },
714    };
715    let user = UserSliceWrite::new(out_ptr, core::mem::size_of::<NetQueueInfo>())?;
716    let bytes = unsafe {
717        core::slice::from_raw_parts(
718            &info as *const NetQueueInfo as *const u8,
719            core::mem::size_of::<NetQueueInfo>(),
720        )
721    };
722    user.copy_from(bytes);
723    Ok(core::mem::size_of::<NetQueueInfo>() as u64)
724}
725
726/// `SYS_NET_EVENT_WAIT`: wait for or poll a queue event.
727///
728/// `timeout_ns == 0` polls and returns `EAGAIN` when no event is pending.
729/// A non-zero timeout currently blocks until the next event: the caller
730/// must use `SYS_NET_RX_BATCH` / the mapped ring to make progress.
731pub fn sys_net_event_wait(dev: u64, qid: u64, timeout_ns: u64) -> Result<u64, SyscallError> {
732    if qid > u16::MAX as u64 {
733        return Err(SyscallError::InvalidArgument);
734    }
735    let queue = queue_from_handle(dev, qid as u16)?;
736    let mut seen = 0u64;
737    if timeout_ns == 0 {
738        return if queue.event.poll(&mut seen) {
739            Ok(1)
740        } else {
741            Err(SyscallError::Again)
742        };
743    }
744    queue.event.wait(&mut seen);
745    queue.header().irq_count.fetch_add(1, Ordering::Relaxed);
746    Ok(1)
747}
748
749/// `SYS_NET_FEATURES`: get or set negotiated features.
750///
751/// `set != 0` ORs `mask` into the current set and returns the new mask;
752/// otherwise returns the current mask.
753pub fn sys_net_features(dev: u64, mask: u64, set: u64) -> Result<u64, SyscallError> {
754    let queue = queue_from_handle(dev, 0)?;
755    let mut current = queue.feature_mask();
756    if set != 0 {
757        current |= mask & features::ALL;
758        queue.set_features(current);
759    }
760    Ok(current)
761}
762
763/// Reset the per-queue event sequence.  Used by restarting strates.
764pub fn sys_net_event_reset(dev: u64, qid: u64) -> Result<u64, SyscallError> {
765    let queue = queue_from_handle(dev, qid as u16)?;
766    // A new registration means the old wakeup was consumed.
767    queue.event.notify();
768    Ok(0)
769}
770
771/// `SYS_NET_DEVICE_EVENT`: drain one hotplug/link event.
772pub fn sys_net_device_event(out_ptr: u64) -> Result<u64, SyscallError> {
773    // Only the capability is required: the device may already be gone.
774    nic_cap_present(CapPermissions {
775        read: true,
776        write: false,
777        execute: false,
778        grant: false,
779        revoke: false,
780    })?;
781
782    let Some(device_event) = hotplug::pop() else {
783        return Err(SyscallError::Again);
784    };
785    let event = NetEvent {
786        kind: device_event.kind,
787        qid: 0,
788        flags: 0,
789        epoch: device_event.epoch,
790        _pad: 0,
791        data: device_event.resource,
792    };
793    let user = UserSliceWrite::new(out_ptr, core::mem::size_of::<NetEvent>())?;
794    let bytes = unsafe {
795        core::slice::from_raw_parts(
796            &event as *const NetEvent as *const u8,
797            core::mem::size_of::<NetEvent>(),
798        )
799    };
800    user.copy_from(bytes);
801    Ok(0)
802}
803
804/// `SYS_NET_QUIESCE`: stop a device before hot-unplug/reset.
805pub fn sys_net_quiesce(dev: u64) -> Result<u64, SyscallError> {
806    let device = nic_from_handle(dev, CapPermissions::read_write())?;
807    device.quiesce().map_err(|_| SyscallError::IoError)?;
808    hotplug::push(hotplug::DeviceEvent::new(
809        event::QUIESCE,
810        nic::device_resource_id(&device) as u64,
811        device.epoch(),
812        0,
813    ));
814    Ok(0)
815}
816
817/// `SYS_NET_RESUME`: resume a quiesced device.
818pub fn sys_net_resume(dev: u64) -> Result<u64, SyscallError> {
819    let device = nic_from_handle(dev, CapPermissions::read_write())?;
820    device.resume().map_err(|_| SyscallError::IoError)?;
821    hotplug::push(hotplug::DeviceEvent::new(
822        event::RESUME,
823        nic::device_resource_id(&device) as u64,
824        device.epoch(),
825        0,
826    ));
827    Ok(0)
828}
829
830// Keep `NetEvent` and `event` referenced for the port notification path
831// implemented by the device manager in P3.
832const _: u32 = event::RX_READY;
833const _: usize = core::mem::size_of::<NetEvent>();
834const _: usize = core::mem::size_of::<NetFrameDesc>();
835const _: usize = NET_POOL_SLOTS;