xref: /DragonOS/kernel/crates/klog_types/src/lib.rs (revision b5b571e02693d91eb6918d3b7561e088c3e7ee81)
1 #![no_std]
2 #![feature(const_refs_to_cell)]
3 #![feature(const_size_of_val)]
4 #![allow(clippy::needless_return)]
5 
6 extern crate alloc;
7 use core::{fmt::Debug, mem::size_of_val};
8 
9 use alloc::format;
10 use kdepends::{memoffset::offset_of, thingbuf::StaticThingBuf};
11 
12 #[repr(C)]
13 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
14 pub struct AllocatorLog {
15     /// 日志的id
16     pub id: u64,
17     /// 日志类型
18     pub type_: AllocatorLogType,
19     /// 日志的时间
20     pub time: u64,
21 
22     /// 日志的来源
23     pub source: LogSource,
24 
25     /// 日志的来源pid
26     pub pid: Option<usize>,
27 
28     pub checksum: u64,
29 }
30 
31 impl AllocatorLog {
32     /// 创建一个日志
33     ///
34     /// ## 参数
35     ///
36     /// - `id`:日志的id
37     /// - `type_`:日志类型
38     /// - `source`:日志来源
39     /// - `pid`:日志来源的pid
40     /// - `time`:日志的时间
41     pub fn new(
42         id: u64,
43         type_: AllocatorLogType,
44         source: LogSource,
45         pid: Option<usize>,
46         time: u64,
47     ) -> Self {
48         let mut x = Self {
49             id,
50             type_,
51             time,
52             source,
53             pid,
54             checksum: 0,
55         };
56         let checksum = Self::calculate_checksum(&x);
57         x.checksum = checksum;
58         return x;
59     }
60 
61     pub const fn zeroed() -> Self {
62         return Self {
63             id: 0,
64             type_: AllocatorLogType::Undefined,
65             time: 0,
66             source: LogSource::Undefined,
67             pid: None,
68             checksum: 0,
69         };
70     }
71 
72     /// 计算日志的校验和
73     pub fn calculate_checksum(value: &Self) -> u64 {
74         let buf = unsafe {
75             core::slice::from_raw_parts(
76                 value as *const _ as *const u8,
77                 core::mem::size_of::<Self>() - core::mem::size_of::<u64>(),
78             )
79         };
80         let checksum = kdepends::crc::crc64::crc64_be(0, buf);
81         return checksum;
82     }
83 
84     /// 验证日志的校验和
85     pub fn validate_checksum(&self) -> bool {
86         let checksum = Self::calculate_checksum(self);
87         return checksum == self.checksum;
88     }
89 
90     /// 当前日志是否有效
91     pub fn is_valid(&self) -> bool {
92         if !self.validate_checksum() {
93             return false;
94         }
95 
96         if self.id == 0 {
97             return false;
98         }
99 
100         return true;
101     }
102 }
103 
104 impl PartialOrd for AllocatorLog {
105     fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
106         Some(self.cmp(other))
107     }
108 }
109 
110 impl Ord for AllocatorLog {
111     fn cmp(&self, other: &Self) -> core::cmp::Ordering {
112         return self.id.cmp(&other.id);
113     }
114 }
115 
116 /// 内存分配器日志类型
117 #[repr(C)]
118 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
119 pub enum AllocatorLogType {
120     Undefined,
121     Alloc(AllocLogItem),
122     AllocZeroed(AllocLogItem),
123     Free(AllocLogItem),
124 }
125 
126 #[repr(C)]
127 #[derive(Copy, Clone, PartialEq, Eq)]
128 pub struct AllocLogItem {
129     pub layout: core::alloc::Layout,
130     pub vaddr: Option<usize>,
131     pub paddr: Option<usize>,
132 }
133 
134 impl AllocLogItem {
135     pub fn new(layout: core::alloc::Layout, vaddr: Option<usize>, paddr: Option<usize>) -> Self {
136         return Self {
137             layout,
138             vaddr,
139             paddr,
140         };
141     }
142 }
143 
144 impl Debug for AllocLogItem {
145     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
146         f.debug_struct("AllocLogItem")
147             .field("layout", &self.layout)
148             .field(
149                 "vaddr",
150                 &format_args!("{:#x}", *self.vaddr.as_ref().unwrap_or(&0)),
151             )
152             .field(
153                 "paddr",
154                 &format_args!("{:#x}", self.paddr.as_ref().unwrap_or(&0)),
155             )
156             .finish()
157     }
158 }
159 
160 #[repr(u8)]
161 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
162 pub enum LogSource {
163     Undefined = 0,
164     Bump = 1,
165     Buddy = 2,
166     Slab = 3,
167 }
168 
169 pub struct MMLogCycle;
170 
171 impl MMLogCycle {
172     pub const fn new() -> Self {
173         Self {}
174     }
175 }
176 
177 impl kdepends::thingbuf::Recycle<AllocatorLog> for MMLogCycle {
178     fn new_element(&self) -> AllocatorLog {
179         AllocatorLog::zeroed()
180     }
181 
182     fn recycle(&self, element: &mut AllocatorLog) {
183         *element = AllocatorLog::zeroed();
184     }
185 }
186 
187 /// 内存分配器日志通道
188 #[repr(C)]
189 pub struct MMLogChannel<const CAP: usize> {
190     pub magic: u32,
191     /// 日志元素的大小
192     pub element_size: u32,
193     /// 日志通道每个槽的大小(字节)
194     pub slot_size: u32,
195     pub capacity: u64,
196     pub slots_offset: u64,
197     pub buf: StaticThingBuf<AllocatorLog, CAP, MMLogCycle>,
198 }
199 
200 impl<const CAP: usize> Debug for MMLogChannel<CAP> {
201     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
202         f.debug_struct("MMLogChannel")
203             .field("magic", &format!("{:#x}", self.magic))
204             .field("element_size", &self.element_size)
205             .field("capacity", &self.capacity)
206             .field("slots_offset", &self.slots_offset)
207             .field(
208                 "buf",
209                 &format!(
210                     "StaticThingBuf<AllocatorLog, {}, MMLogCycle>",
211                     self.capacity
212                 ),
213             )
214             .finish()
215     }
216 }
217 
218 impl<const CAP: usize> MMLogChannel<CAP> {
219     /// 日志通道的魔数
220     pub const MM_LOG_CHANNEL_MAGIC: u32 = 0x4d4c4348;
221 
222     /// 创建一个大小为`capacity`日志通道
223     pub const fn new(capacity: usize) -> Self {
224         let buffer = StaticThingBuf::with_recycle(MMLogCycle::new());
225         assert!(buffer.offset_of_slots() != 0);
226         let slot_total_size = size_of_val(&buffer) - buffer.offset_of_slots();
227         let slot_size = slot_total_size / capacity;
228         assert!(slot_size != 0);
229         assert!(slot_size > size_of_val(&AllocatorLog::zeroed()));
230 
231         let r = Self {
232             magic: Self::MM_LOG_CHANNEL_MAGIC,
233             element_size: core::mem::size_of::<AllocatorLog>() as u32,
234             capacity: capacity as u64,
235             slot_size: slot_size as u32,
236             slots_offset: (offset_of!(MMLogChannel<CAP>, buf) + buffer.offset_of_slots()) as u64,
237             buf: buffer,
238         };
239 
240         return r;
241     }
242 }
243