zenith-linux 0.1.0

Zenith Linux 平台抽象层:AF_XDP Socket、UMEM 内存管理、四环操作(Fill/RX/TX/Completion)、描述符安全校验引擎
Documentation
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
//! Zenith Linux - Linux 平台抽象层
//!
//! 本 crate 提供 Linux 平台特有的系统抽象,包括:
//! - AF_XDP Socket 管理与零拷贝数据通路
//! - UMEM 内存管理(mmap、锁页、HugePage)
//! - 四环操作封装(Fill/RX/TX/Completion)
//! - 描述符安全校验引擎与事务化所有权迁移
//! - 系统调用封装与能力探测
//!
//! # 架构原则
//! 1. 上层接口零 unsafe,所有 unsafe 封装在本 crate 内部
//! 2. 单队列单 Owner,无锁、无共享、无阻塞
//! 3. 预分配优先,热路径零堆分配
//! 4. 描述符全生命周期追踪,守恒等式恒成立
//!
//! # unsafe 使用
//! crate 顶层 `#![deny(unsafe_code)]`(与 workspace lint 一致),unsafe 仅
//! 在以下位置精确放开,绝不 crate 级全开:
//! - 本文件 `page_size()` / `get_kernel_version()`:libc FFI 的安全封装,
//!   以 item 级 `#[allow(unsafe_code)]` 精确放开;
//! - affinity / netif / ring / syscalls / umem / xsk / io_uring(feature 门控)
//!   七个模块:文件顶部 `#![allow(unsafe_code)]` + 模块文档说明 unsafe 不可
//!   避免的原因(系统调用 / mmap 共享内存 / C 结构体 FFI)。
//!
//! descriptor / error 模块不含任何 unsafe,不做任何放开。
//! 所有 unsafe 块均附 SAFETY 注释。

#![deny(unsafe_code)]
// AF_XDP/io_uring/libbpf 仅 Linux 可用:非 Linux 目标下本 crate 整体为空,
// 依赖方(zenith-runtime 等)以同样的 cfg(target_os = "linux") 门控使用点。
#![cfg(target_os = "linux")]

pub mod affinity;
pub mod descriptor;
pub mod error;
pub mod netif;
pub mod ring;
pub mod syscalls;
pub mod umem;
pub mod xsk;

// O2: io_uring 异步 IO 批量化封装(可选,需启用 io_uring feature)
#[cfg(feature = "io_uring")]
pub mod io_uring;

pub use affinity::{online_cpu_count, set_thread_affinity, set_thread_affinity_range, AffinityError};
pub use descriptor::{Descriptor, DescriptorEngine, DescriptorType, XdpDesc};
pub use error::{LinuxError, Result};
pub use netif::{if_nametoindex, NetIfError};
pub use ring::{RingOffsets, RingType, XDP_RING_NEED_WAKEUP, XskRing};
pub use syscalls::{
    pipe2, recvmmsg, sendfile, sendmmsg, splice, splice_bidirectional, FdGuard, SpliceFlags,
    MAX_BATCH_DATAGRAMS,
};
pub use umem::{UmemConfig, UmemManager};
pub use xsk::{XskConfig, XskSocket, XskState};

// O2: io_uring 批量 IO 提交器重导出
#[cfg(feature = "io_uring")]
pub use io_uring::{Completion, IoUringBatcher, UdpBatchIo};

use std::sync::atomic::{AtomicBool, Ordering};

/// 返回系统页面大小(字节)。
///
/// # 实现
/// 通过 `libc::sysconf(_SC_PAGESIZE)` 查询,失败时回退到 4096(大多数 Linux 平台的默认)。
/// 该值为只读系统属性,首次调用后不变,因此由调用方缓存。
///
/// unsafe 不可避免:`libc::sysconf` 为 libc FFI 查询只读系统属性。
#[allow(unsafe_code)]
pub fn page_size() -> usize {
    // SAFETY: sysconf 仅对只读全局系统属性进行查询,无副作用,无内存安全影响。
    let ps = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
    if ps <= 0 {
        4096usize
    } else {
        ps as usize
    }
}

/// Linux 平台信息
#[derive(Debug, Clone)]
pub struct LinuxPlatform {
    /// 内核版本
    pub kernel_version: String,
    /// 架构
    pub architecture: String,
}

impl LinuxPlatform {
    /// 创建新的 Linux 平台实例
    pub fn new(kernel_version: String, architecture: String) -> Self {
        Self {
            kernel_version,
            architecture,
        }
    }

    /// 检查是否支持 eBPF
    ///
    /// eBPF 需要内核 4.4+
    pub fn supports_ebpf(&self) -> bool {
        let major_minor: Vec<&str> = self.kernel_version.split('.').collect();
        if major_minor.len() >= 2
            && let Ok(major) = major_minor[0].parse::<u32>()
                && let Ok(minor) = major_minor[1].parse::<u32>() {
                    return major > 4 || (major == 4 && minor >= 4);
                }
        false
    }

    /// 检查是否支持 AF_XDP
    ///
    /// AF_XDP 需要内核 4.18+
    pub fn supports_af_xdp(&self) -> bool {
        let major_minor: Vec<&str> = self.kernel_version.split('.').collect();
        if major_minor.len() >= 2
            && let Ok(major) = major_minor[0].parse::<u32>()
                && let Ok(minor) = major_minor[1].parse::<u32>() {
                    return major > 4 || (major == 4 && minor >= 18);
                }
        false
    }

    /// 检查是否支持 HugePage
    pub fn supports_hugepage(&self) -> bool {
        // 检查 /proc/meminfo 中是否存在 HugePages
        if let Ok(content) = std::fs::read_to_string("/proc/meminfo") {
            content.contains("HugePages_Total")
        } else {
            false
        }
    }

    /// 检查是否支持 XDP Native 模式
    ///
    /// 需要内核 5.3+ 和网卡驱动支持
    pub fn supports_xdp_native(&self) -> bool {
        let major_minor: Vec<&str> = self.kernel_version.split('.').collect();
        if major_minor.len() >= 2
            && let Ok(major) = major_minor[0].parse::<u32>()
                && let Ok(minor) = major_minor[1].parse::<u32>() {
                    return major > 5 || (major == 5 && minor >= 3);
                }
        false
    }

    /// 检测当前平台能力
    ///
    /// # 返回
    /// * `PlatformCapabilities` - 平台能力集合
    pub fn detect_capabilities(&self) -> PlatformCapabilities {
        PlatformCapabilities {
            ebpf: self.supports_ebpf(),
            af_xdp: self.supports_af_xdp(),
            hugepage: self.supports_hugepage(),
            xdp_native: self.supports_xdp_native(),
            xdp_generic: self.supports_ebpf(), // Generic 模式依赖 eBPF
            mlock: true, // 通常都支持
        }
    }
}

/// 平台能力集合
#[derive(Debug, Clone, Copy)]
#[derive(Default)]
pub struct PlatformCapabilities {
    /// 是否支持 eBPF
    pub ebpf: bool,
    /// 是否支持 AF_XDP
    pub af_xdp: bool,
    /// 是否支持 HugePage
    pub hugepage: bool,
    /// 是否支持 XDP Native 模式
    pub xdp_native: bool,
    /// 是否支持 XDP Generic 模式
    pub xdp_generic: bool,
    /// 是否支持 mlock
    pub mlock: bool,
}


/// 初始化状态
static INITIALIZED: AtomicBool = AtomicBool::new(false);

/// 初始化 Zenith Linux 平台
///
/// 必须在使用任何 AF_XDP 功能之前调用。
///
/// # 返回
/// * `Result<()>` - 初始化结果
pub fn init() -> Result<()> {
    if INITIALIZED.swap(true, Ordering::SeqCst) {
        // 已初始化
        return Ok(());
    }

    // 检测内核版本
    let kernel_version = get_kernel_version();

    let platform = LinuxPlatform::new(kernel_version, get_architecture());

    // 验证必要能力
    let caps = platform.detect_capabilities();

    if !caps.ebpf {
        return Err(LinuxError::Unsupported(
            "eBPF not supported (kernel 4.4+ required)".to_string(),
        ));
    }

    Ok(())
}

/// 获取内核版本
///
/// unsafe 不可避免:`uname` 系统调用与 `CStr::from_ptr` 均为 libc FFI,
/// 本函数是其安全封装(含 /proc 回退路径),故 item 级精确放开。
// SAFETY: 以下 unsafe 块涉及三个不安全操作,均已验证为安全:
// 1. std::mem::zeroed::<utsname>():utsname 为栈分配,在调用期间有效;
//    zeroed() 返回全零初始化的结构体,满足 C 结构体要求。
// 2. libc::uname(&mut utsname):uname() 是纯系统调用,向提供的缓冲区写入内核信息;
//    缓冲区为栈分配,生命周期覆盖整个调用,不可能发生 use-after-free。
// 3. CStr::from_ptr(utsname.release.as_ptr()):POSIX 规范保证 uname() 返回时
//    release 字段以 null 结尾,因此 from_ptr 不会读取越界内存。
#[allow(unsafe_code)]
fn get_kernel_version() -> String {
    // 尝试从 uname 获取
    let mut utsname: libc::utsname = unsafe { std::mem::zeroed() };
    let ret = unsafe { libc::uname(&mut utsname) };
    if ret == 0 {
        let release = unsafe {
            std::ffi::CStr::from_ptr(utsname.release.as_ptr())
        };
        return release.to_string_lossy().to_string();
    }

    // 尝试从 /proc/sys/kernel/osrelease 读取
    std::fs::read_to_string("/proc/sys/kernel/osrelease")
        .unwrap_or_else(|_| "unknown".to_string())
        .trim()
        .to_string()
}

/// 获取架构
fn get_architecture() -> String {
    if cfg!(target_arch = "x86_64") {
        "x86_64".to_string()
    } else if cfg!(target_arch = "aarch64") {
        "aarch64".to_string()
    } else {
        "unknown".to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_linux_platform_creation() {
        let platform = LinuxPlatform::new("5.15.0".to_string(), "x86_64".to_string());
        assert_eq!(platform.kernel_version, "5.15.0");
        assert_eq!(platform.architecture, "x86_64");
    }

    #[test]
    fn test_supports_ebpf() {
        let modern = LinuxPlatform::new("5.15.0".to_string(), "x86_64".to_string());
        assert!(modern.supports_ebpf());

        let old = LinuxPlatform::new("4.1.0".to_string(), "x86_64".to_string());
        assert!(!old.supports_ebpf());

        let edge = LinuxPlatform::new("4.4.0".to_string(), "x86_64".to_string());
        assert!(edge.supports_ebpf());
    }

    #[test]
    fn test_supports_af_xdp() {
        let modern = LinuxPlatform::new("5.15.0".to_string(), "x86_64".to_string());
        assert!(modern.supports_af_xdp());

        let old = LinuxPlatform::new("4.17.0".to_string(), "x86_64".to_string());
        assert!(!old.supports_af_xdp());
    }

    #[test]
    fn test_supports_xdp_native() {
        let modern = LinuxPlatform::new("5.15.0".to_string(), "x86_64".to_string());
        assert!(modern.supports_xdp_native());

        let old = LinuxPlatform::new("5.2.0".to_string(), "x86_64".to_string());
        assert!(!old.supports_xdp_native());
    }

    #[test]
    fn test_detect_capabilities() {
        let platform = LinuxPlatform::new("5.15.0".to_string(), "x86_64".to_string());
        let caps = platform.detect_capabilities();
        assert!(caps.ebpf);
        assert!(caps.af_xdp);
        assert!(caps.xdp_native);
        assert!(caps.xdp_generic);
    }

    #[test]
    fn test_platform_init() {
        // 测试在支持的平台上初始化
        let result = init();
        // 可能成功也可能失败(取决于内核版本)
        let _ = result;
    }

    #[test]
    fn test_public_api_reexports() {
        let _desc: Descriptor = Descriptor::default();
        let _xdp: XdpDesc = XdpDesc::zero();
        let _desc_type: DescriptorType = DescriptorType::DataFrame;
        let _engine: DescriptorEngine = DescriptorEngine::new(1024).unwrap();
        let _err: LinuxError = LinuxError::Unsupported("test".to_string());
        let _result: Result<()> = Ok(());
        let _ring: XskRing = XskRing::new(RingType::Rx, 16).unwrap();
        let _ring_type: RingType = RingType::Fill;
        let _offsets: RingOffsets = RingOffsets {
            producer: 0,
            consumer: 0,
            desc: 0,
            flags: 0,
            len: 0,
        };
        let _umem_config: UmemConfig = UmemConfig::default();
        let _xsk_config: XskConfig = XskConfig::default();
        let _state: XskState = XskState::Created;
    }

    #[test]
    fn test_platform_capabilities_default() {
        let caps = PlatformCapabilities::default();
        assert!(!caps.ebpf);
        assert!(!caps.af_xdp);
        assert!(!caps.hugepage);
        assert!(!caps.xdp_native);
        assert!(!caps.xdp_generic);
        assert!(!caps.mlock);
    }

    #[test]
    fn test_platform_capabilities_copy() {
        let caps = PlatformCapabilities {
            ebpf: true,
            af_xdp: true,
            hugepage: false,
            xdp_native: true,
            xdp_generic: true,
            mlock: true,
        };
        let copied = caps;
        assert!(copied.ebpf);
        assert!(copied.af_xdp);
        assert!(copied.xdp_native);
    }

    #[test]
    fn test_linux_platform_clone() {
        let platform = LinuxPlatform::new("5.15.0".to_string(), "x86_64".to_string());
        let cloned = platform.clone();
        assert_eq!(cloned.kernel_version, "5.15.0");
        assert_eq!(cloned.architecture, "x86_64");
    }

    #[test]
    fn test_kernel_version_boundary_4_4() {
        let platform = LinuxPlatform::new("4.4.0".to_string(), "x86_64".to_string());
        assert!(platform.supports_ebpf());
    }

    #[test]
    fn test_kernel_version_boundary_4_3() {
        let platform = LinuxPlatform::new("4.3.9".to_string(), "x86_64".to_string());
        assert!(!platform.supports_ebpf());
    }

    #[test]
    fn test_kernel_version_boundary_4_18() {
        let platform = LinuxPlatform::new("4.18.0".to_string(), "x86_64".to_string());
        assert!(platform.supports_af_xdp());
    }

    #[test]
    fn test_kernel_version_boundary_4_17() {
        let platform = LinuxPlatform::new("4.17.99".to_string(), "x86_64".to_string());
        assert!(!platform.supports_af_xdp());
    }

    #[test]
    fn test_kernel_version_boundary_5_3() {
        let platform = LinuxPlatform::new("5.3.0".to_string(), "x86_64".to_string());
        assert!(platform.supports_xdp_native());
    }

    #[test]
    fn test_kernel_version_boundary_5_2() {
        let platform = LinuxPlatform::new("5.2.99".to_string(), "x86_64".to_string());
        assert!(!platform.supports_xdp_native());
    }

    #[test]
    fn test_kernel_version_major_gt_4() {
        let platform = LinuxPlatform::new("6.1.0".to_string(), "x86_64".to_string());
        assert!(platform.supports_ebpf());
        assert!(platform.supports_af_xdp());
        assert!(platform.supports_xdp_native());
    }

    #[test]
    fn test_invalid_kernel_version_format() {
        let platform = LinuxPlatform::new("invalid".to_string(), "x86_64".to_string());
        assert!(!platform.supports_ebpf());
        assert!(!platform.supports_af_xdp());
        assert!(!platform.supports_xdp_native());
    }

    #[test]
    fn test_partial_kernel_version() {
        let platform = LinuxPlatform::new("5".to_string(), "x86_64".to_string());
        assert!(!platform.supports_ebpf());
    }

    #[test]
    fn test_xdp_generic_equals_ebpf() {
        let modern = LinuxPlatform::new("5.15.0".to_string(), "x86_64".to_string());
        let caps = modern.detect_capabilities();
        assert_eq!(caps.xdp_generic, caps.ebpf);
    }
}