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
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
//! Zenith Linux 错误类型
//!
//! 统一的错误处理体系,覆盖 AF_XDP、UMEM、Ring、描述符校验等操作

use std::fmt;

/// Linux 平台操作错误
#[derive(Debug)]
pub enum LinuxError {
    /// AF_XDP 操作错误
    Xsk(XskError),
    /// UMEM 操作错误
    Umem(UmemError),
    /// Ring 操作错误
    Ring(RingError),
    /// 描述符校验错误
    Descriptor(DescriptorError),
    /// 系统调用错误
    Syscall {
        /// 系统调用名称
        syscall: &'static str,
        /// errno
        errno: i32,
    },
    /// 资源不足
    InsufficientResources(String),
    /// 不支持的操作
    Unsupported(String),
}

impl fmt::Display for LinuxError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LinuxError::Xsk(e) => write!(f, "AF_XDP error: {}", e),
            LinuxError::Umem(e) => write!(f, "UMEM error: {}", e),
            LinuxError::Ring(e) => write!(f, "Ring error: {}", e),
            LinuxError::Descriptor(e) => write!(f, "Descriptor error: {}", e),
            LinuxError::Syscall { syscall, errno } => {
                write!(f, "Syscall '{}' failed with errno {}", syscall, errno)
            }
            LinuxError::InsufficientResources(msg) => {
                write!(f, "Insufficient resources: {}", msg)
            }
            LinuxError::Unsupported(msg) => write!(f, "Unsupported: {}", msg),
        }
    }
}

impl std::error::Error for LinuxError {}

impl From<XskError> for LinuxError {
    fn from(e: XskError) -> Self {
        LinuxError::Xsk(e)
    }
}

impl From<UmemError> for LinuxError {
    fn from(e: UmemError) -> Self {
        LinuxError::Umem(e)
    }
}

impl From<RingError> for LinuxError {
    fn from(e: RingError) -> Self {
        LinuxError::Ring(e)
    }
}

impl From<DescriptorError> for LinuxError {
    fn from(e: DescriptorError) -> Self {
        LinuxError::Descriptor(e)
    }
}

/// AF_XDP 操作错误
#[derive(Debug)]
pub enum XskError {
    /// Socket 创建失败
    SocketCreate(String),
    /// Socket 选项设置失败
    SocketOption(String),
    /// Bind 失败
    BindFailed(String),
    /// 队列不存在
    QueueNotFound(u32),
    /// XSK 已绑定
    AlreadyBound,
    /// XSK 未绑定
    NotBound,
    /// XSK 关闭失败
    CloseFailed(String),
    /// 唤醒内核轮询失败(XDP_RING_NEED_WAKEUP 路径的 sendto/notify 失败)
    NotifyFailed(String),
    /// 描述符无效
    InvalidDescriptor(u64),
    /// 状态迁移非法(当前状态 → 期望状态)
    InvalidState(String),
}

impl fmt::Display for XskError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            XskError::SocketCreate(msg) => write!(f, "Socket creation failed: {}", msg),
            XskError::SocketOption(msg) => write!(f, "Socket option failed: {}", msg),
            XskError::BindFailed(msg) => write!(f, "Bind failed: {}", msg),
            XskError::QueueNotFound(q) => write!(f, "Queue not found: {}", q),
            XskError::AlreadyBound => write!(f, "XSK already bound"),
            XskError::NotBound => write!(f, "XSK not bound"),
            XskError::CloseFailed(msg) => write!(f, "Close failed: {}", msg),
            XskError::NotifyFailed(msg) => write!(f, "XSK wakeup notify failed: {}", msg),
            XskError::InvalidDescriptor(d) => write!(f, "Invalid descriptor: {}", d),
            XskError::InvalidState(msg) => write!(f, "Invalid XSK state: {}", msg),
        }
    }
}

impl std::error::Error for XskError {}

/// UMEM 操作错误
#[derive(Debug)]
pub enum UmemError {
    /// mmap 失败
    MmapFailed(String),
    /// 内存锁定失败
    LockFailed(String),
    /// 内存地址未对齐
    NotAligned {
        /// 实际对齐
        actual: usize,
        /// 期望对齐
        expected: usize,
    },
    /// 内存大小不足
    InsufficientSize {
        /// 实际大小
        actual: usize,
        /// 需要大小
        required: usize,
    },
    /// HugePage 不可用
    HugePageNotAvailable,
    /// UMEM 已创建
    AlreadyCreated,
    /// UMEM 未创建
    NotCreated,
    /// munmap 失败
    MunmapFailed(String),
}

impl fmt::Display for UmemError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            UmemError::MmapFailed(msg) => write!(f, "mmap failed: {}", msg),
            UmemError::LockFailed(msg) => write!(f, "mlock failed: {}", msg),
            UmemError::NotAligned { actual, expected } => {
                write!(f, "Memory not aligned: actual {}, expected {}", actual, expected)
            }
            UmemError::InsufficientSize { actual, required } => {
                write!(
                    f,
                    "Insufficient memory: actual {} bytes, required {} bytes",
                    actual, required
                )
            }
            UmemError::HugePageNotAvailable => write!(f, "HugePage not available"),
            UmemError::AlreadyCreated => write!(f, "UMEM already created"),
            UmemError::NotCreated => write!(f, "UMEM not created"),
            UmemError::MunmapFailed(msg) => write!(f, "munmap failed: {}", msg),
        }
    }
}

impl std::error::Error for UmemError {}

/// Ring 操作错误
#[derive(Debug)]
pub enum RingError {
    /// Ring 已满
    RingFull,
    /// Ring 已空
    RingEmpty,
    /// 描述符无效
    InvalidDescriptor(u64),
    /// 索引越界
    IndexOutOfBounds {
        /// 索引
        index: u32,
        /// 容量
        capacity: u32,
    },
    /// 生产者/消费者冲突
    ProducerConsumerConflict,
    /// 批量大小超出
    BatchSizeExceeded {
        /// 请求大小
        requested: u32,
        /// 最大允许
        maximum: u32,
    },
    /// Ring 偏移/长度非法
    InvalidOffsets(String),
}

impl fmt::Display for RingError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RingError::RingFull => write!(f, "Ring is full"),
            RingError::RingEmpty => write!(f, "Ring is empty"),
            RingError::InvalidDescriptor(d) => write!(f, "Invalid descriptor: {}", d),
            RingError::IndexOutOfBounds { index, capacity } => {
                write!(
                    f,
                    "Ring index {} out of bounds (capacity {})",
                    index, capacity
                )
            }
            RingError::ProducerConsumerConflict => {
                write!(f, "Producer-consumer conflict")
            }
            RingError::BatchSizeExceeded { requested, maximum } => {
                write!(
                    f,
                    "Batch size {} exceeded maximum {}",
                    requested, maximum
                )
            }
            RingError::InvalidOffsets(msg) => write!(f, "Invalid ring offsets: {}", msg),
        }
    }
}

impl std::error::Error for RingError {}

/// 描述符校验错误
#[derive(Debug)]
pub enum DescriptorError {
    /// 描述符为零(无效)
    ZeroDescriptor,
    /// 描述符超出范围
    OutOfRange {
        /// 描述符值
        descriptor: u64,
        /// 最大值
        max_valid: u64,
    },
    /// 描述符已释放
    AlreadyFreed(u64),
    /// 描述符已在使用
    AlreadyInUse(u64),
    /// 帧已被引擎分配(位图已置位),重复分配会破坏守恒等式(fail-closed)
    AlreadyAllocated(u64),
    /// 帧容量超出 20-bit 帧索引域(> 2^20),构造期 fail-closed
    InvalidCapacity(u64),
    /// 所有权不匹配
    OwnershipMismatch {
        /// 期望所有者
        expected: u32,
        /// 实际所有者
        actual: u32,
    },
    /// 代际不匹配
    GenerationMismatch {
        /// 期望代际
        expected: u64,
        /// 实际代际
        actual: u64,
    },
    /// 帧移位(log2(frame_size))非法
    ///
    /// 合法区间 11..=15(帧大小 2048..=32768 字节)。超出区间的移位会使
    /// `frame_index << frame_shift` 在 debug 触发 shift-overflow panic、
    /// 在 release 触发移位掩码静默产生错误地址,故必须构造期拒绝(fail-closed)。
    InvalidFrameShift(u32),
    /// 事务失败
    TransactionFailed(String),
}

impl fmt::Display for DescriptorError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DescriptorError::ZeroDescriptor => write!(f, "Zero descriptor (invalid)"),
            DescriptorError::OutOfRange {
                descriptor,
                max_valid,
            } => write!(
                f,
                "Descriptor {} out of range (max valid: {})",
                descriptor, max_valid
            ),
            DescriptorError::AlreadyFreed(d) => write!(f, "Descriptor {} already freed", d),
            DescriptorError::AlreadyInUse(d) => write!(f, "Descriptor {} already in use", d),
            // 字段名不能与 formatter 形参 `f` 同名:别名绑定避免 write! 把
            // `&u64` 当成输出目标(E0599),也防止数字被静默吞掉。
            DescriptorError::AlreadyAllocated(frame) => {
                write!(f, "Frame {} already allocated", frame)
            }
            DescriptorError::InvalidCapacity(c) => write!(
                f,
                "Descriptor capacity {c} exceeds 20-bit frame index domain (max 2^20 frames)"
            ),
            DescriptorError::OwnershipMismatch { expected, actual } => {
                write!(
                    f,
                    "Ownership mismatch: expected {}, actual {}",
                    expected, actual
                )
            }
            DescriptorError::InvalidFrameShift(shift) => write!(
                f,
                "Invalid frame_shift {shift}: must be in 11..=15 (frame size 2048..=32768 bytes)"
            ),
            DescriptorError::GenerationMismatch { expected, actual } => {
                write!(
                    f,
                    "Generation mismatch: expected {}, actual {}",
                    expected, actual
                )
            }
            DescriptorError::TransactionFailed(msg) => {
                write!(f, "Transaction failed: {}", msg)
            }
        }
    }
}

impl std::error::Error for DescriptorError {}

/// 结果类型别名
pub type Result<T> = std::result::Result<T, LinuxError>;

// 错误严重级别统一以 zenith-core 为正统(全 workspace 唯一定义):
// 本 crate 不再自有定义,re-export 保持 `zenith_linux::error::ErrorSeverity` 路径兼容。
// 语义映射:原 `Fatal`(致命级,系统不可用)→ `ErrorSeverity::Critical`。
pub use zenith_foundation::error::ErrorSeverity;

impl LinuxError {
    /// 获取错误严重级别
    pub fn severity(&self) -> ErrorSeverity {
        match self {
            LinuxError::Syscall { .. } => ErrorSeverity::Error,
            LinuxError::InsufficientResources(_) => ErrorSeverity::Critical,
            LinuxError::Unsupported(_) => ErrorSeverity::Critical,
            LinuxError::Xsk(e) => e.severity(),
            LinuxError::Umem(e) => e.severity(),
            LinuxError::Ring(e) => e.severity(),
            LinuxError::Descriptor(e) => e.severity(),
        }
    }

    /// 是否为系统调用错误
    pub fn is_syscall_error(&self) -> bool {
        matches!(self, LinuxError::Syscall { .. })
    }

    /// 是否为配置错误
    pub fn is_config_error(&self) -> bool {
        matches!(
            self,
            LinuxError::Xsk(XskError::SocketOption(_))
                | LinuxError::Umem(UmemError::NotAligned { .. })
                | LinuxError::Umem(UmemError::InsufficientSize { .. })
                | LinuxError::Ring(RingError::BatchSizeExceeded { .. })
                | LinuxError::Descriptor(DescriptorError::OutOfRange { .. })
        )
    }

    /// 是否为资源错误
    pub fn is_resource_error(&self) -> bool {
        matches!(
            self,
            LinuxError::InsufficientResources(_)
                | LinuxError::Umem(UmemError::MmapFailed(_))
                | LinuxError::Umem(UmemError::LockFailed(_))
                | LinuxError::Ring(RingError::RingFull)
                | LinuxError::Ring(RingError::RingEmpty)
        )
    }
}

impl XskError {
    /// 获取错误严重级别
    pub fn severity(&self) -> ErrorSeverity {
        match self {
            XskError::SocketCreate(_) => ErrorSeverity::Critical,
            XskError::SocketOption(_) => ErrorSeverity::Error,
            XskError::BindFailed(_) => ErrorSeverity::Error,
            XskError::QueueNotFound(_) => ErrorSeverity::Warning,
            XskError::AlreadyBound => ErrorSeverity::Warning,
            XskError::NotBound => ErrorSeverity::Warning,
            XskError::CloseFailed(_) => ErrorSeverity::Warning,
            XskError::NotifyFailed(_) => ErrorSeverity::Error,
            XskError::InvalidDescriptor(_) => ErrorSeverity::Error,
            XskError::InvalidState(_) => ErrorSeverity::Warning,
        }
    }
}

impl UmemError {
    /// 获取错误严重级别
    pub fn severity(&self) -> ErrorSeverity {
        match self {
            UmemError::MmapFailed(_) => ErrorSeverity::Critical,
            UmemError::LockFailed(_) => ErrorSeverity::Error,
            UmemError::NotAligned { .. } => ErrorSeverity::Error,
            UmemError::InsufficientSize { .. } => ErrorSeverity::Error,
            UmemError::HugePageNotAvailable => ErrorSeverity::Warning,
            UmemError::AlreadyCreated => ErrorSeverity::Warning,
            UmemError::NotCreated => ErrorSeverity::Warning,
            UmemError::MunmapFailed(_) => ErrorSeverity::Warning,
        }
    }
}

impl RingError {
    /// 获取错误严重级别
    pub fn severity(&self) -> ErrorSeverity {
        match self {
            RingError::RingFull => ErrorSeverity::Warning,
            RingError::RingEmpty => ErrorSeverity::Info,
            RingError::InvalidDescriptor(_) => ErrorSeverity::Error,
            RingError::IndexOutOfBounds { .. } => ErrorSeverity::Error,
            RingError::ProducerConsumerConflict => ErrorSeverity::Critical,
            RingError::BatchSizeExceeded { .. } => ErrorSeverity::Warning,
            RingError::InvalidOffsets(_) => ErrorSeverity::Error,
        }
    }
}

impl DescriptorError {
    /// 获取错误严重级别
    pub fn severity(&self) -> ErrorSeverity {
        match self {
            DescriptorError::ZeroDescriptor => ErrorSeverity::Error,
            DescriptorError::OutOfRange { .. } => ErrorSeverity::Error,
            DescriptorError::AlreadyFreed(_) => ErrorSeverity::Warning,
            DescriptorError::AlreadyInUse(_) => ErrorSeverity::Warning,
            DescriptorError::AlreadyAllocated(_) => ErrorSeverity::Warning,
            DescriptorError::InvalidCapacity(_) => ErrorSeverity::Error,
            DescriptorError::OwnershipMismatch { .. } => ErrorSeverity::Error,
            DescriptorError::InvalidFrameShift(_) => ErrorSeverity::Error,
            DescriptorError::GenerationMismatch { .. } => ErrorSeverity::Warning,
            DescriptorError::TransactionFailed(_) => ErrorSeverity::Error,
        }
    }
}

impl From<LinuxError> for std::io::Error {
    fn from(err: LinuxError) -> Self {
        match err {
            LinuxError::Syscall { errno, .. } => std::io::Error::from_raw_os_error(errno),
            LinuxError::Umem(UmemError::MmapFailed(msg)) => {
                std::io::Error::new(std::io::ErrorKind::OutOfMemory, msg)
            }
            LinuxError::Umem(UmemError::LockFailed(msg)) => {
                std::io::Error::new(std::io::ErrorKind::PermissionDenied, msg)
            }
            LinuxError::InsufficientResources(msg) => {
                std::io::Error::new(std::io::ErrorKind::OutOfMemory, msg)
            }
            other => std::io::Error::other(other.to_string()),
        }
    }
}

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

    #[test]
    fn test_linux_error_xsk_display() {
        let err = LinuxError::Xsk(XskError::SocketCreate("test error".to_string()));
        let display = format!("{}", err);
        assert!(display.contains("AF_XDP error"));
        assert!(display.contains("Socket creation failed"));
        assert!(display.contains("test error"));
    }

    #[test]
    fn test_linux_error_umem_display() {
        let err = LinuxError::Umem(UmemError::MmapFailed("mmap test".to_string()));
        let display = format!("{}", err);
        assert!(display.contains("UMEM error"));
        assert!(display.contains("mmap failed"));
        assert!(display.contains("mmap test"));
    }

    #[test]
    fn test_linux_error_ring_display() {
        let err = LinuxError::Ring(RingError::RingFull);
        let display = format!("{}", err);
        assert!(display.contains("Ring error"));
        assert!(display.contains("Ring is full"));
    }

    #[test]
    fn test_linux_error_descriptor_display() {
        let err = LinuxError::Descriptor(DescriptorError::ZeroDescriptor);
        let display = format!("{}", err);
        assert!(display.contains("Descriptor error"));
        assert!(display.contains("Zero descriptor"));
    }

    #[test]
    fn test_linux_error_syscall_display() {
        let err = LinuxError::Syscall {
            syscall: "socket",
            errno: 13,
        };
        let display = format!("{}", err);
        assert!(display.contains("Syscall 'socket' failed"));
        assert!(display.contains("errno 13"));
    }

    #[test]
    fn test_linux_error_insufficient_resources_display() {
        let err = LinuxError::InsufficientResources("out of memory".to_string());
        let display = format!("{}", err);
        assert!(display.contains("Insufficient resources"));
        assert!(display.contains("out of memory"));
    }

    #[test]
    fn test_linux_error_unsupported_display() {
        let err = LinuxError::Unsupported("feature not available".to_string());
        let display = format!("{}", err);
        assert!(display.contains("Unsupported"));
        assert!(display.contains("feature not available"));
    }

    #[test]
    fn test_xsk_error_variants_display() {
        let cases = vec![
            (
                XskError::SocketCreate("a".to_string()),
                "Socket creation failed",
            ),
            (
                XskError::SocketOption("b".to_string()),
                "Socket option failed",
            ),
            (XskError::BindFailed("c".to_string()), "Bind failed"),
            (XskError::QueueNotFound(5), "Queue not found: 5"),
            (XskError::AlreadyBound, "XSK already bound"),
            (XskError::NotBound, "XSK not bound"),
            (XskError::CloseFailed("d".to_string()), "Close failed"),
            (
                XskError::NotifyFailed("e".to_string()),
                "XSK wakeup notify failed",
            ),
            (XskError::InvalidDescriptor(42), "Invalid descriptor: 42"),
        ];

        for (err, expected) in cases {
            let display = format!("{}", err);
            assert!(display.contains(expected), "Expected '{}' in '{}'", expected, display);
        }
    }

    #[test]
    fn test_umem_error_variants_display() {
        let cases = vec![
            (UmemError::MmapFailed("a".to_string()), "mmap failed"),
            (UmemError::LockFailed("b".to_string()), "mlock failed"),
            (
                UmemError::NotAligned {
                    actual: 100,
                    expected: 4096,
                },
                "Memory not aligned",
            ),
            (
                UmemError::InsufficientSize {
                    actual: 100,
                    required: 200,
                },
                "Insufficient memory",
            ),
            (UmemError::HugePageNotAvailable, "HugePage not available"),
            (UmemError::AlreadyCreated, "UMEM already created"),
            (UmemError::NotCreated, "UMEM not created"),
            (UmemError::MunmapFailed("c".to_string()), "munmap failed"),
        ];

        for (err, expected) in cases {
            let display = format!("{}", err);
            assert!(display.contains(expected), "Expected '{}' in '{}'", expected, display);
        }
    }

    #[test]
    fn test_ring_error_variants_display() {
        let cases = vec![
            (RingError::RingFull, "Ring is full"),
            (RingError::RingEmpty, "Ring is empty"),
            (RingError::InvalidDescriptor(123), "Invalid descriptor: 123"),
            (
                RingError::IndexOutOfBounds {
                    index: 10,
                    capacity: 5,
                },
                "Ring index 10 out of bounds",
            ),
            (RingError::ProducerConsumerConflict, "Producer-consumer conflict"),
            (
                RingError::BatchSizeExceeded {
                    requested: 100,
                    maximum: 50,
                },
                "Batch size 100 exceeded maximum 50",
            ),
        ];

        for (err, expected) in cases {
            let display = format!("{}", err);
            assert!(display.contains(expected), "Expected '{}' in '{}'", expected, display);
        }
    }

    #[test]
    fn test_descriptor_error_variants_display() {
        let cases = vec![
            (DescriptorError::ZeroDescriptor, "Zero descriptor"),
            (
                DescriptorError::OutOfRange {
                    descriptor: 100,
                    max_valid: 50,
                },
                "Descriptor 100 out of range",
            ),
            (DescriptorError::AlreadyFreed(42), "Descriptor 42 already freed"),
            (DescriptorError::AlreadyInUse(99), "Descriptor 99 already in use"),
            (
                DescriptorError::AlreadyAllocated(7),
                "Frame 7 already allocated",
            ),
            (
                DescriptorError::InvalidCapacity(1 << 21),
                "exceeds 20-bit frame index domain",
            ),
            (
                DescriptorError::OwnershipMismatch {
                    expected: 1,
                    actual: 2,
                },
                "Ownership mismatch",
            ),
            (
                DescriptorError::GenerationMismatch {
                    expected: 3,
                    actual: 5,
                },
                "Generation mismatch",
            ),
            (
                DescriptorError::TransactionFailed("tx fail".to_string()),
                "Transaction failed",
            ),
        ];

        for (err, expected) in cases {
            let display = format!("{}", err);
            assert!(display.contains(expected), "Expected '{}' in '{}'", expected, display);
        }
    }

    #[test]
    fn test_error_from_conversions() {
        let xsk_err = XskError::AlreadyBound;
        let linux_err: LinuxError = xsk_err.into();
        assert!(matches!(linux_err, LinuxError::Xsk(XskError::AlreadyBound)));

        let umem_err = UmemError::NotCreated;
        let linux_err: LinuxError = umem_err.into();
        assert!(matches!(linux_err, LinuxError::Umem(UmemError::NotCreated)));

        let ring_err = RingError::RingFull;
        let linux_err: LinuxError = ring_err.into();
        assert!(matches!(linux_err, LinuxError::Ring(RingError::RingFull)));

        let desc_err = DescriptorError::ZeroDescriptor;
        let linux_err: LinuxError = desc_err.into();
        assert!(matches!(
            linux_err,
            LinuxError::Descriptor(DescriptorError::ZeroDescriptor)
        ));
    }

    #[test]
    fn test_error_severity() {
        assert_eq!(
            LinuxError::Syscall {
                syscall: "test",
                errno: 1
            }
            .severity(),
            ErrorSeverity::Error
        );
        assert_eq!(
            LinuxError::InsufficientResources("x".to_string()).severity(),
            ErrorSeverity::Critical
        );
        assert_eq!(
            LinuxError::Unsupported("x".to_string()).severity(),
            ErrorSeverity::Critical
        );
        assert_eq!(
            LinuxError::Xsk(XskError::SocketCreate("x".to_string())).severity(),
            ErrorSeverity::Critical
        );
        assert_eq!(
            LinuxError::Xsk(XskError::QueueNotFound(0)).severity(),
            ErrorSeverity::Warning
        );
        assert_eq!(
            LinuxError::Umem(UmemError::MmapFailed("x".to_string())).severity(),
            ErrorSeverity::Critical
        );
        assert_eq!(
            LinuxError::Umem(UmemError::HugePageNotAvailable).severity(),
            ErrorSeverity::Warning
        );
        assert_eq!(
            LinuxError::Ring(RingError::RingEmpty).severity(),
            ErrorSeverity::Info
        );
        assert_eq!(
            LinuxError::Ring(RingError::ProducerConsumerConflict).severity(),
            ErrorSeverity::Critical
        );
        assert_eq!(
            LinuxError::Descriptor(DescriptorError::ZeroDescriptor).severity(),
            ErrorSeverity::Error
        );
        assert_eq!(
            LinuxError::Descriptor(DescriptorError::AlreadyFreed(0)).severity(),
            ErrorSeverity::Warning
        );
    }

    #[test]
    fn test_error_classification() {
        let syscall_err = LinuxError::Syscall {
            syscall: "socket",
            errno: 1,
        };
        assert!(syscall_err.is_syscall_error());
        assert!(!syscall_err.is_config_error());
        assert!(!syscall_err.is_resource_error());

        let config_err = LinuxError::Umem(UmemError::NotAligned {
            actual: 100,
            expected: 4096,
        });
        assert!(!config_err.is_syscall_error());
        assert!(config_err.is_config_error());
        assert!(!config_err.is_resource_error());

        let resource_err = LinuxError::InsufficientResources("oom".to_string());
        assert!(!resource_err.is_syscall_error());
        assert!(!resource_err.is_config_error());
        assert!(resource_err.is_resource_error());

        let ring_full = LinuxError::Ring(RingError::RingFull);
        assert!(ring_full.is_resource_error());
    }

    #[test]
    fn test_linux_error_to_io_error() {
        let syscall_err = LinuxError::Syscall {
            syscall: "test",
            errno: 12, // ENOMEM
        };
        let io_err: std::io::Error = syscall_err.into();
        assert_eq!(io_err.raw_os_error(), Some(12));

        let mmap_err = LinuxError::Umem(UmemError::MmapFailed("failed".to_string()));
        let io_err: std::io::Error = mmap_err.into();
        assert_eq!(io_err.kind(), std::io::ErrorKind::OutOfMemory);

        let lock_err = LinuxError::Umem(UmemError::LockFailed("denied".to_string()));
        let io_err: std::io::Error = lock_err.into();
        assert_eq!(io_err.kind(), std::io::ErrorKind::PermissionDenied);

        let oom_err = LinuxError::InsufficientResources("oom".to_string());
        let io_err: std::io::Error = oom_err.into();
        assert_eq!(io_err.kind(), std::io::ErrorKind::OutOfMemory);

        let other_err = LinuxError::Xsk(XskError::AlreadyBound);
        let io_err: std::io::Error = other_err.into();
        assert_eq!(io_err.kind(), std::io::ErrorKind::Other);
    }

    #[test]
    fn test_error_trait_implementation() {
        let err: Box<dyn std::error::Error> =
            Box::new(LinuxError::Syscall {
                syscall: "test",
                errno: 1,
            });
        assert!(err.source().is_none());

        let err: Box<dyn std::error::Error> = Box::new(XskError::AlreadyBound);
        assert!(err.source().is_none());

        let err: Box<dyn std::error::Error> = Box::new(UmemError::NotCreated);
        assert!(err.source().is_none());

        let err: Box<dyn std::error::Error> = Box::new(RingError::RingEmpty);
        assert!(err.source().is_none());

        let err: Box<dyn std::error::Error> = Box::new(DescriptorError::ZeroDescriptor);
        assert!(err.source().is_none());
    }

    #[test]
    fn test_result_type_alias() {
        let ok: Result<i32> = Ok(42);
        assert!(ok.is_ok());

        let err: Result<i32> = Err(LinuxError::Unsupported("test".to_string()));
        assert!(err.is_err());
    }

    #[test]
    fn test_error_debug_format() {
        let err = LinuxError::Syscall {
            syscall: "mmap",
            errno: 12,
        };
        let debug = format!("{:?}", err);
        assert!(debug.contains("Syscall"));
        assert!(debug.contains("mmap"));
        assert!(debug.contains("12"));
    }
}