packetvisor 1.0.1

Packetvisor is a Raw Packet I/O framework based on the Rust language. It can process packets much faster than Standard Sockets through the Linux Kernel's eXpress Data Path(XDP).
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
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
//!
//! # Packetvisor
//!
//! `Packetvisor` is a Raw Packet I/O framework based on the Rust language.
//! It can process packets much faster than `Standard Sockets` through the
//! Linux Kernel's `eXpress Data Path (XDP)`.
//!
//! ## Key features
//!
//! **1. Bypassing the Network Stack in the Linux Kernel and Achieving Zero-Copy with `XDP`**
//! * Packetvisor completely bypasses the Network Stack in the Linux kernel using `XDP`,
//! reducing unnecessary overhead in the packet processing.
//!
//! **2. High-Speed Packet Processing with the `pv::Nic` Structure**
//! * `Packetvisor` uses the `pv::Nic` structure to attach to specific Network Interface.
//! This structure utilizes `XDP_SOCKET(XSK)` to directly process transmit
//! and receive packets, allowing applications to directly transmit and
//! receive packets in the application space. This helps to simplify the
//! data processing process and improve performance.
//!
//! **3. Easy Development with Rust**
//! * `Packetvisor` is developed based on the Rust language, so you can use
//! Rust to create high-performance _firewalls_ and implement _tunneling
//! protocols_ with just a few dozen lines of code.
//!
//! **4. Automatically detects XDP mode**
//! * `Packetvisor` supports both `XDP` `Native(=DRV)` and `Generic(=SKB)` modes,
//! and the mode selection is automatically determined by `Packetvisor`.
//!
//! ## Examples
//! Various examples for packet _echo_, _filtering_, _forwarding_, etc.
//! can be found in the [examples] directory.
//!
//! [examples]: https://github.com/tsnlab/packetvisor/tree/master/examples

mod bindings {
    #![allow(non_upper_case_globals)]
    #![allow(non_camel_case_types)]
    #![allow(non_snake_case)]
    #![allow(dead_code)]
    #![allow(clippy::all)]

    #[cfg(docsrs)]
    include!("bindings.rs");
    #[cfg(not(docsrs))]
    include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
}

use bindings::*;
use pnet::datalink::{interfaces, NetworkInterface};
use std::alloc::{alloc_zeroed, Layout};
use std::cell::RefCell;
use std::collections::hash_set::HashSet;
use std::convert::TryInto;
use std::ffi::{c_char, c_int, c_void, CStr, CString};
use std::ptr::copy;
use std::rc::Rc;
use std::thread;
use std::time::Duration;

use libc::strerror;

const DEFAULT_HEADROOM: usize = 256;

/********************************************************************
 *
 * Global Variable (for Singleton-Pattern)
 *
 *******************************************************************/
static mut POOL: Option<Pool> = None;

/********************************************************************
 *
 * Structures
 *
 *******************************************************************/
#[derive(Debug)]
struct BufferPool {
    chunk_size: usize,
    #[allow(dead_code)]
    chunk_count: usize,

    pool: HashSet<u64>,

    buffer: *mut c_void, // buffer address.

    fq_size: usize,
    cq_size: usize,
}

#[derive(Debug)]
struct Pool {
    chunk_size: usize,

    umem: *mut xsk_umem,
    buffer_pool: Rc<RefCell<BufferPool>>,

    umem_fq: xsk_ring_prod,
    umem_cq: xsk_ring_cons,

    refcount: usize,
}

/// NIC Structure that supports Packetvisor
#[derive(Debug)]
pub struct Nic {
    /// Attached network interface information.
    /// (ex. `interface name`, `L2-3 address`, etc.)
    pub interface: NetworkInterface,
    xsk: *mut xsk_socket,

    /* XSK rings */
    rxq: xsk_ring_cons,
    txq: xsk_ring_prod,
    umem_fq: xsk_ring_prod,
    umem_cq: xsk_ring_cons,
}

/// Packet Structure used by Packetvisor
#[derive(Debug)]
pub struct Packet {
    /// payload offset from `buffer` pointing the start of payload.
    pub start: usize,
    /// payload offset from `buffer` point the end of payload.
    pub end: usize,
    /// total size of buffer.
    pub buffer_size: usize,
    /// buffer address.
    pub buffer: *mut u8,
    private: *mut c_void, // DO NOT touch this.

    buffer_pool: Rc<RefCell<BufferPool>>,
}

struct ReservedResult {
    count: u32,
    idx: u32,
}

/********************************************************************
 *
 * Implementation
 *
 *******************************************************************/
impl BufferPool {
    fn new(
        chunk_size: usize,
        chunk_count: usize,
        buffer: *mut c_void,
        fq_size: usize,
        cq_size: usize,
    ) -> Self {
        /* initialize UMEM chunk information */
        let pool = (0..chunk_count)
            .map(|i| (i * chunk_size).try_into().unwrap())
            .collect::<HashSet<u64>>();
        Self {
            chunk_size,
            chunk_count,
            pool,
            buffer,
            fq_size,
            cq_size,
        }
    }

    fn alloc_addr(&mut self) -> Result<u64, &'static str> {
        if let Some(addr) = self.pool.iter().next() {
            let addr = *addr;
            self.pool.remove(&addr);
            Ok(addr)
        } else {
            Err("Chunk Pool is empty")
        }
    }

    fn free_addr(&mut self, chunk_addr: u64) {
        // Align
        let chunk_addr = chunk_addr - (chunk_addr % self.chunk_size as u64);

        #[cfg(debug_assertions)]
        if self.pool.contains(&chunk_addr) {
            eprintln!("Chunk Pool already contains chunk_addr: {}", chunk_addr);
        }

        self.pool.insert(chunk_addr);

        #[cfg(debug_assertions)]
        if self.pool.len() > self.chunk_count {
            eprintln!("Chunk Pool is overflowed");
        }
    }

    /// Reserve FQ and UMEM chunks as much as **len
    fn reserve_fq(&mut self, fq: &mut xsk_ring_prod, len: usize) -> Result<usize, &'static str> {
        let mut cq_idx = 0;
        let reserved = unsafe { xsk_ring_prod__reserve(fq, len as u32, &mut cq_idx) };

        // Allocate UMEM chunks into fq
        for i in 0..reserved {
            unsafe {
                *xsk_ring_prod__fill_addr(fq, cq_idx + i) = self.alloc_addr()?;
            }
        }

        // Notify kernel of allocation UMEM chunks into fq as much as **reserved
        unsafe {
            xsk_ring_prod__submit(fq, reserved);
        }

        Ok(reserved.try_into().unwrap())
    }

    /// Reserve for txq
    fn reserve_txq(
        &mut self,
        txq: &mut xsk_ring_prod,
        len: usize,
    ) -> Result<ReservedResult, &'static str> {
        let mut idx = 0;
        let count = unsafe { xsk_ring_prod__reserve(txq, len as u32, &mut idx) };

        Ok(ReservedResult { count, idx })
    }

    /// Free packet metadata and UMEM chunks as much as the # of filled slots in CQ
    fn release(&mut self, cq: &mut xsk_ring_cons, len: usize) -> Result<u32, String> {
        let mut cq_idx = 0;
        let count = unsafe {
            // Fetch the number of filled slots(the # of packets completely sent) in cq
            xsk_ring_cons__peek(cq, len as u32, &mut cq_idx)
        };
        if count > 0 {
            // Notify kernel that cq has empty slots with **filled (Dequeue)
            unsafe {
                xsk_ring_cons__release(cq, count);
            }
        }

        Ok(count)
    }

    fn recv(
        &mut self,
        chunk_pool_rc: &Rc<RefCell<Self>>,
        len: usize,
        _xsk: &*mut xsk_socket,
        rxq: &mut xsk_ring_cons,
        fq: &mut xsk_ring_prod,
    ) -> Vec<Packet> {
        let mut packets = Vec::<Packet>::with_capacity(len);

        let mut rx_idx = 0;
        let received = unsafe { xsk_ring_cons__peek(rxq, len as u32, &mut rx_idx) };

        if received == 0 {
            return packets;
        }

        for i in 0..received {
            let mut packet = Packet::new(chunk_pool_rc);
            let rx_desc = unsafe { xsk_ring_cons__rx_desc(&*rxq, rx_idx + i).as_ref().unwrap() };
            packet.end += rx_desc.len as usize;
            packet.buffer_size = self.chunk_size;
            packet.buffer = unsafe {
                xsk_umem__get_data(self.buffer, rx_desc.addr)
                    .cast::<u8>()
                    .sub(DEFAULT_HEADROOM)
            };
            packet.private = (rx_desc.addr - DEFAULT_HEADROOM as u64) as *mut c_void;

            packets.push(packet);
        }

        unsafe {
            xsk_ring_cons__release(rxq, received);
        }

        self.reserve_fq(fq, packets.len()).unwrap();

        /*
         * XSK manages interrupts through xsk_ring_prod__needs_wakup().
         *
         * If Packetvisor is assigned to core indexes [0] or [1], the Rx interrupt does not work properly.
         * This significantly degrades Packetvisor performance.
         * To resolve this issue, the interrupt is woken up whenever Recv() is called.
         */
        unsafe {
            if xsk_ring_prod__needs_wakeup(&*fq) != 0 {
                libc::recvfrom(
                    xsk_socket__fd(*_xsk),
                    std::ptr::null_mut::<libc::c_void>(),
                    0 as libc::size_t,
                    libc::MSG_DONTWAIT,
                    std::ptr::null_mut::<libc::sockaddr>(),
                    std::ptr::null_mut::<u32>(),
                );
            }
        }

        packets
    }

    fn send(
        &mut self,
        packets: &mut [Packet],
        xsk: &*mut xsk_socket,
        tx: &mut xsk_ring_prod,
        cq: &mut xsk_ring_cons,
    ) -> usize {
        self.release(cq, self.cq_size).unwrap();
        let reserved = self.reserve_txq(tx, packets.len()).unwrap();

        for (i, pkt) in packets.iter().enumerate().take(reserved.count as usize) {
            // Insert packets to be sent into the TX ring (Enqueue)
            let tx_desc = unsafe {
                xsk_ring_prod__tx_desc(tx, reserved.idx + i as u32)
                    .as_mut()
                    .unwrap()
            };
            tx_desc.addr = pkt.private as u64 + pkt.start as u64;
            tx_desc.len = (pkt.end - pkt.start) as u32;
        }

        // NOTE: Dropping packet here will cause Already Borrowed error.
        // So, we should drain packets after this function call.
        // packets.drain(0..reserved.count as usize);

        unsafe {
            xsk_ring_prod__submit(&mut *tx, reserved.count);
            if xsk_ring_prod__needs_wakeup(tx) != 0 {
                // Interrupt the kernel to send packets
                libc::sendto(
                    xsk_socket__fd(*xsk),
                    std::ptr::null::<libc::c_void>(),
                    0 as libc::size_t,
                    libc::MSG_DONTWAIT,
                    std::ptr::null::<libc::sockaddr>(),
                    0 as libc::socklen_t,
                );
            }
        }

        reserved.count.try_into().unwrap()
    }
}

impl Pool {
    fn new() -> Result<Self, String> {
        let umem_ptr = alloc_zeroed_layout::<xsk_umem>()?;
        let fq_ptr = alloc_zeroed_layout::<xsk_ring_prod>()?;
        let cq_ptr = alloc_zeroed_layout::<xsk_ring_cons>()?;

        let umem = umem_ptr.cast::<xsk_umem>(); // umem is needed to be dealloc after using packetvisor library.
        let fq = unsafe { std::ptr::read(fq_ptr.cast::<xsk_ring_prod>()) };
        let cq = unsafe { std::ptr::read(cq_ptr.cast::<xsk_ring_cons>()) };

        let chunk_pool = BufferPool::new(0, 0, std::ptr::null_mut(), 0, 0);

        let chunk_size = 0;
        let refcount = 0;

        let obj = Self {
            chunk_size,
            umem,
            buffer_pool: Rc::new(RefCell::new(chunk_pool)),
            umem_fq: fq,
            umem_cq: cq,
            refcount,
        };

        Ok(obj)
    }

    fn init(
        chunk_size: usize,
        chunk_count: usize,
        fq_size: usize,
        cq_size: usize,
    ) -> Result<(), String> {
        if unsafe { POOL.as_ref() }.is_none() {
            let mut pool_obj = Pool::new()?;
            pool_obj.re_init(chunk_size, chunk_count, fq_size, cq_size)?;
            unsafe { POOL = Some(pool_obj) };
        }

        Ok(())
    }

    fn re_init(
        &mut self,
        chunk_size: usize,
        chunk_count: usize,
        fq_size: usize,
        cq_size: usize,
    ) -> Result<(), String> {
        let umem_buffer_size = chunk_size * chunk_count;
        let mmap_address = unsafe {
            libc::mmap(
                std::ptr::null_mut::<libc::c_void>(),
                umem_buffer_size,
                libc::PROT_READ | libc::PROT_WRITE,
                libc::MAP_PRIVATE | libc::MAP_ANONYMOUS,
                -1, // fd
                0,  // offset
            )
        };

        if mmap_address == libc::MAP_FAILED {
            return Err("Failed to allocate memory for UMEM.".to_string());
        }

        let umem_cfg = xsk_umem_config {
            fill_size: fq_size as u32,
            comp_size: cq_size as u32,
            frame_size: chunk_size as u32,
            frame_headroom: XSK_UMEM__DEFAULT_FRAME_HEADROOM,
            flags: XSK_UMEM__DEFAULT_FLAGS,
        };

        let ret = unsafe {
            xsk_umem__create(
                &mut self.umem,
                mmap_address,
                umem_buffer_size as u64,
                &mut self.umem_fq,
                &mut self.umem_cq,
                &umem_cfg,
            )
        };

        if ret != 0 {
            unsafe {
                // Unmap first
                libc::munmap(mmap_address, umem_buffer_size);
            }
            let msg = unsafe {
                CStr::from_ptr(strerror(-ret))
                    .to_string_lossy()
                    .into_owned()
            };

            return Err(format!("Failed to create UMEM: {}", msg));
        }

        let chunk_pool = BufferPool::new(chunk_size, chunk_count, mmap_address, fq_size, cq_size);
        let mut borrow_buffer_pool = self.buffer_pool.borrow_mut();
        *borrow_buffer_pool = chunk_pool;

        self.chunk_size = chunk_size;

        Ok(())
    }

    fn alloc_addr(&mut self) -> Result<u64, &'static str> {
        self.buffer_pool.borrow_mut().alloc_addr()
    }

    /// Allocate packet from UMEM
    fn try_alloc_packet(&mut self) -> Option<Packet> {
        match self.alloc_addr() {
            Err(_) => None,
            Ok(idx) => {
                let mut packet: Packet = Packet::new(&self.buffer_pool);
                packet.buffer_size = self.chunk_size;
                packet.buffer =
                    unsafe { xsk_umem__get_data(self.buffer_pool.borrow().buffer, idx) as *mut u8 };
                packet.private = idx as *mut c_void;

                Some(packet)
            }
        }
    }
}

impl Nic {
    /// # Description
    /// Attaching `pv::Nic` to network interface
    /// # Arguments
    /// `if_name` - network interface name \
    /// `chunk_size` - total size of packet payload \
    /// `chunk_count` - total count of chunk \
    /// `fq_size` - filling ring size \
    /// `cq_size` - completion ring size \
    /// `tx_size` - tx ring size \
    /// `rx_size` - rx ring size \
    /// # Returns
    /// On success, returns `pv::Nic` bound to the network interface. \
    /// On failure, returns an error string.
    pub fn new(
        if_name: &str,
        chunk_size: usize,
        chunk_count: usize,
        fq_size: usize,
        cq_size: usize,
        tx_size: usize,
        rx_size: usize,
    ) -> Result<Nic, String> {
        let interface = interfaces()
            .into_iter()
            .find(|elem| elem.name.as_str() == if_name)
            .ok_or(format!("Interface {} not found.", if_name))?;

        let xsk_ptr = alloc_zeroed_layout::<xsk_socket>()?;
        let rx_ptr = alloc_zeroed_layout::<xsk_ring_cons>()?;
        let tx_ptr = alloc_zeroed_layout::<xsk_ring_prod>()?;
        let fq_ptr = alloc_zeroed_layout::<xsk_ring_prod>()?;
        let cq_ptr = alloc_zeroed_layout::<xsk_ring_cons>()?;

        /* The result of Pool::init() must be unwrapped using the unwrap() function. \
         * If you do not use unwrap(), the internal fields of the Pool object will not \
         * be properly initialized, which can lead to potential problems.
         *
         * Ex) Fallback between XSK's SKB and DRV modes may not be possible. \
         *     Other unexpected problems may occur. */
        Pool::init(chunk_size, chunk_count, fq_size, cq_size).unwrap();

        let mut nic = unsafe {
            Nic {
                interface: interface.clone(),
                xsk: xsk_ptr.cast::<xsk_socket>(),
                rxq: std::ptr::read(rx_ptr.cast::<xsk_ring_cons>()),
                txq: std::ptr::read(tx_ptr.cast::<xsk_ring_prod>()),
                umem_fq: std::ptr::read(fq_ptr.cast::<xsk_ring_prod>()),
                umem_cq: std::ptr::read(cq_ptr.cast::<xsk_ring_cons>()),
            }
        };

        match Nic::open(
            &mut nic,
            chunk_size,
            chunk_count,
            fq_size,
            cq_size,
            tx_size,
            rx_size,
        ) {
            Ok(_) => {
                unsafe {
                    POOL.as_mut().unwrap().refcount += 1;
                };
                Ok(nic)
            }
            Err(e) => {
                // FIXME: Print here is fine. But segfault happened when printing in the caller.
                eprintln!("Failed to open NIC: {}", e);
                Err(e)
            }
        }
    }

    fn open(
        &mut self,
        chunk_size: usize,
        chunk_count: usize,
        fq_size: usize,
        cq_size: usize,
        rx_ring_size: usize,
        tx_ring_size: usize,
    ) -> Result<(), String> {
        let mut xsk_cfg: xsk_socket_config = xsk_socket_config {
            rx_size: rx_ring_size.try_into().unwrap(),
            tx_size: tx_ring_size.try_into().unwrap(),
            __bindgen_anon_1: xsk_socket_config__bindgen_ty_1 { libxdp_flags: 0 },
            xdp_flags: XDP_FLAGS_DRV_MODE,
            bind_flags: XDP_USE_NEED_WAKEUP as u16,
        };
        let if_name = CString::new(self.interface.name.clone()).unwrap();
        let if_ptr = if_name.as_ptr() as *const c_char;

        let ret: c_int = unsafe {
            xsk_socket__create_shared(
                &mut self.xsk,
                if_ptr,
                0,
                POOL.as_mut().unwrap().umem,
                &mut self.rxq,
                &mut self.txq,
                &mut self.umem_fq,
                &mut self.umem_cq,
                &xsk_cfg,
            )
        };

        if ret != 0 {
            match unsafe { POOL.as_ref().unwrap().refcount } {
                0 => {
                    // Pool Full-Fallback
                    unsafe { xsk_umem__delete(POOL.as_mut().unwrap().umem) };
                    thread::sleep(Duration::from_millis(100));
                    unsafe {
                        POOL.as_mut()
                            .unwrap()
                            .re_init(chunk_size, chunk_count, fq_size, cq_size)?
                    };
                }
                refcount if refcount > 0 => {
                    // Pool Semi-Fallback
                    thread::sleep(Duration::from_millis(100));
                }
                _ => {
                    return Err("Pool Fallback failed".to_string());
                }
            }

            xsk_cfg.xdp_flags = XDP_FLAGS_SKB_MODE;
            let ret: c_int = unsafe {
                xsk_socket__create_shared(
                    &mut self.xsk,
                    if_ptr,
                    0,
                    POOL.as_mut().unwrap().umem,
                    &mut self.rxq,
                    &mut self.txq,
                    &mut POOL.as_mut().unwrap().umem_fq,
                    &mut POOL.as_mut().unwrap().umem_cq,
                    &xsk_cfg,
                )
            };

            if ret != 0 {
                let msg = unsafe {
                    CStr::from_ptr(strerror(-ret))
                        .to_string_lossy()
                        .into_owned()
                };
                let message = format!("Error: {}", msg);
                return Err(format!("xsk_socket__create failed: {}", message));
            }
        }

        /*
         * After calling xsk_umem__create(), the fill_q and comp_q of the UMEM are initialized.
         * These are assigned to the first XSK through xsk_socket__create() or  _shared().
         * However, this does not work properly in Rust.
         *
         * Therefore, we stored the fill_q and comp_q in the Pool object before calling xsk_umem__create().
         * After xsk_socket__create() or _shared() finishes, the stored fill_q and comp_q are assigned to the Nic object.
         * This resolves the Segmentation Fault issue.
         */
        if unsafe { POOL.as_ref().unwrap().refcount == 0 } {
            self.umem_fq = unsafe { POOL.as_ref().unwrap().umem_fq };
            self.umem_cq = unsafe { POOL.as_ref().unwrap().umem_cq };

            let fq_ptr = alloc_zeroed_layout::<xsk_ring_prod>()?;
            let cq_ptr = alloc_zeroed_layout::<xsk_ring_cons>()?;
            unsafe {
                POOL.as_mut().unwrap().umem_fq = std::ptr::read(fq_ptr.cast::<xsk_ring_prod>());
                POOL.as_mut().unwrap().umem_cq = std::ptr::read(cq_ptr.cast::<xsk_ring_cons>());
            };
        }

        let fq_size = unsafe { POOL.as_mut().unwrap().buffer_pool.borrow().fq_size };
        unsafe {
            POOL.as_mut()
                .unwrap()
                .buffer_pool
                .borrow_mut()
                .reserve_fq(&mut self.umem_fq, fq_size)?
        };

        Ok(())
    }

    /// # Description
    /// Allocate packet using Pool
    /// # Returns
    /// On success, returns `pv::Packet` with empty payload. \
    /// On failure, returns `None`.
    pub fn alloc_packet(&self) -> Option<Packet> {
        unsafe { POOL.as_mut().unwrap().try_alloc_packet() }
    }

    /// # Description
    /// Send packets \
    /// **\*Sent packets are removed from the vector.**
    /// # Arguments
    /// `packets` - Packets to send
    /// # Returns
    /// Number of packets sent
    pub fn send(&mut self, packets: &mut Vec<Packet>) -> usize {
        let sent_count = unsafe {
            POOL.as_mut().unwrap().buffer_pool.borrow_mut().send(
                packets,
                &self.xsk,
                &mut self.txq,
                &mut self.umem_cq,
            )
        };
        packets.drain(0..sent_count);

        sent_count
    }

    /// # Description
    /// Receive packets
    /// # Arguments
    /// `len` - Number of packets to receive
    /// # Returns
    /// Received packets
    pub fn receive(&mut self, len: usize) -> Vec<Packet> {
        unsafe {
            POOL.as_mut().unwrap().buffer_pool.borrow_mut().recv(
                &POOL.as_mut().unwrap().buffer_pool,
                len,
                &self.xsk,
                &mut self.rxq,
                &mut self.umem_fq,
            )
        }
    }
}

impl Packet {
    fn new(chunk_pool: &Rc<RefCell<BufferPool>>) -> Packet {
        Packet {
            start: DEFAULT_HEADROOM,
            end: DEFAULT_HEADROOM,
            buffer_size: 0,
            buffer: std::ptr::null_mut(),
            private: std::ptr::null_mut(),
            buffer_pool: chunk_pool.clone(),
        }
    }

    /// # Description
    /// Replace payload with new data. \
    /// Data can be memmoved if needed.
    /// # Arguments
    /// `new_data` - new packet payload
    /// # Returns
    /// On success, returns `None` and payload of `pv::Packet` is replaced with `new_data`. \
    /// On failure, returns an error string.
    pub fn replace_data(&mut self, new_data: &[u8]) -> Result<(), String> {
        if new_data.len() <= self.buffer_size {
            unsafe {
                // replace data
                copy(new_data.as_ptr(), self.buffer.offset(0), new_data.len());
                self.start = 0;
                self.end = new_data.len();

                Ok(())
            }
        } else {
            Err(String::from(
                "Data size is over than buffer size of packet.",
            ))
        }
    }

    /// # Description
    /// Get mutable payload
    pub fn get_buffer_mut(&mut self) -> &mut [u8] {
        unsafe {
            std::slice::from_raw_parts_mut(
                self.buffer.offset(self.start.try_into().unwrap()),
                self.end - self.start,
            )
        }
    }

    /// # Description
    /// Resize payload size to `new_size`
    /// # Arguments
    /// `new_size` - new packet payload size
    /// # Returns
    /// On success, return None and payload size of `pv::Packet` is replaced with `new_size`. \
    /// On failure, returns an error string.
    pub fn resize(&mut self, new_size: usize) -> Result<(), String> {
        if new_size > self.buffer_size {
            return Err(format!(
                "The requested size is to large. (Max = {})",
                self.buffer_size
            ));
        }

        let temp_end = self.end;

        if new_size > self.buffer_size - self.start {
            // Need to move data
            unsafe {
                copy(
                    self.buffer.offset(self.start.try_into().unwrap()),
                    self.buffer,
                    temp_end,
                );
            }
            self.start = 0;
            self.end = new_size;
            return Ok(());
        }

        self.end = self.start + new_size;
        Ok(())
    }

    /// # Description
    /// Dump packet payload as hex. Debugging purpose
    #[allow(dead_code)]
    pub fn dump(&self) {
        let chunk_address = self.private as u64;
        let buffer_address: *const u8 = self.buffer.cast_const();

        let length: usize = self.end - self.start;
        let mut count: usize = 0;

        unsafe {
            println!("---packet dump--- chunk addr: {}", chunk_address);

            loop {
                let read_offset: usize = count + self.start;
                let read_address: *const u8 = buffer_address.add(read_offset);
                print!("{:02X?} ", std::ptr::read(read_address));

                count += 1;
                if count == length {
                    break;
                } else if count % 8 == 0 {
                    print!(" ");
                    if count % 16 == 0 {
                        println!();
                    }
                }
            }
        }
        println!("\n-------\n");
    }
}

/********************************************************************
 *
 * Drop
 *
 *******************************************************************/
impl Drop for Pool {
    fn drop(&mut self) {
        // Free UMEM
        let ret: c_int = unsafe { xsk_umem__delete(self.umem) };
        if ret != 0 {
            eprintln!("failed to free umem");
        }
    }
}

impl Drop for Nic {
    // move ownership of nic
    fn drop(&mut self) {
        // xsk delete
        unsafe {
            xsk_socket__delete(self.xsk);
        }

        unsafe {
            POOL.as_mut().unwrap().refcount -= 1;
        };
    }
}

impl Drop for Packet {
    fn drop(&mut self) {
        self.buffer_pool.borrow_mut().free_addr(self.private as u64);
    }
}

/********************************************************************
 *
 * Other functions
 *
 *******************************************************************/
fn alloc_zeroed_layout<T: 'static>() -> Result<*mut u8, String> {
    let ptr;
    unsafe {
        let layout = Layout::new::<T>();
        ptr = alloc_zeroed(layout);
    }
    if ptr.is_null() {
        Err("failed to allocate memory".to_string())
    } else {
        Ok(ptr)
    }
}