xref: /DragonOS/kernel/src/mm/mmio_buddy.rs (revision a7eb62a47a8d701b90a14f83cc9028cfed07c268)
1*a7eb62a4Shoumkh use crate::libs::spinlock::{SpinLock, SpinLockGuard};
2c2481452Shoumkh use crate::{
3c2481452Shoumkh     arch::asm::current::current_pcb,
4c2481452Shoumkh     include::bindings::bindings::{
5c2481452Shoumkh         initial_mm, mm_create_vma, mm_unmap, vm_area_del, vm_area_free, vm_area_struct, vm_flags_t,
6c2481452Shoumkh         vma_find, EINVAL, ENOMEM, EPERM, MMIO_BASE, MMIO_TOP, PAGE_1G_SHIFT, PAGE_1G_SIZE,
7c2481452Shoumkh         PAGE_2M_SIZE, PAGE_4K_SHIFT, PAGE_4K_SIZE, VM_DONTCOPY, VM_IO,
8c2481452Shoumkh     },
9c2481452Shoumkh     kdebug, kerror,
10c2481452Shoumkh };
11c2481452Shoumkh use alloc::{boxed::Box, collections::LinkedList, vec::Vec};
12c2481452Shoumkh use core::{mem, ptr::null_mut};
13c2481452Shoumkh 
14c2481452Shoumkh // 最大的伙伴块的幂
15c2481452Shoumkh const MMIO_BUDDY_MAX_EXP: u32 = PAGE_1G_SHIFT;
16c2481452Shoumkh // 最小的伙伴块的幂
17c2481452Shoumkh const MMIO_BUDDY_MIN_EXP: u32 = PAGE_4K_SHIFT;
18c2481452Shoumkh // 内存池数组的范围
19c2481452Shoumkh const MMIO_BUDDY_REGION_COUNT: u32 = MMIO_BUDDY_MAX_EXP - MMIO_BUDDY_MIN_EXP + 1;
20c2481452Shoumkh 
21c2481452Shoumkh lazy_static! {
22c2481452Shoumkh     pub static ref MMIO_POOL: MmioBuddyMemPool = MmioBuddyMemPool::new();
23c2481452Shoumkh }
24c2481452Shoumkh 
25c2481452Shoumkh pub enum MmioResult {
26c2481452Shoumkh     SUCCESS,
27c2481452Shoumkh     EINVAL,
28c2481452Shoumkh     ENOFOUND,
29c2481452Shoumkh     WRONGEXP,
30c2481452Shoumkh     ISEMPTY,
31c2481452Shoumkh }
32c2481452Shoumkh 
33c2481452Shoumkh /// @brief buddy内存池
34c2481452Shoumkh pub struct MmioBuddyMemPool {
35c2481452Shoumkh     pool_start_addr: u64,
36c2481452Shoumkh     pool_size: u64,
37c2481452Shoumkh     free_regions: [SpinLock<MmioFreeRegionList>; MMIO_BUDDY_REGION_COUNT as usize],
38c2481452Shoumkh }
39c2481452Shoumkh impl Default for MmioBuddyMemPool {
40c2481452Shoumkh     fn default() -> Self {
41c2481452Shoumkh         MmioBuddyMemPool {
42c2481452Shoumkh             pool_start_addr: MMIO_BASE as u64,
43c2481452Shoumkh             pool_size: (MMIO_TOP - MMIO_BASE) as u64,
44c2481452Shoumkh             free_regions: unsafe { mem::zeroed() },
45c2481452Shoumkh         }
46c2481452Shoumkh     }
47c2481452Shoumkh }
48c2481452Shoumkh impl MmioBuddyMemPool {
49c2481452Shoumkh     fn new() -> Self {
50c2481452Shoumkh         return MmioBuddyMemPool {
51c2481452Shoumkh             ..Default::default()
52c2481452Shoumkh         };
53c2481452Shoumkh     }
54c2481452Shoumkh 
55c2481452Shoumkh     /// @brief 创建新的地址区域结构体
56c2481452Shoumkh     ///
57c2481452Shoumkh     /// @param vaddr 虚拟地址
58c2481452Shoumkh     ///
59c2481452Shoumkh     /// @return 创建好的地址区域结构体
60*a7eb62a4Shoumkh     fn create_region(&self, vaddr: u64) -> Box<MmioBuddyAddrRegion> {
61c2481452Shoumkh         let mut region: Box<MmioBuddyAddrRegion> = Box::new(MmioBuddyAddrRegion::new());
62c2481452Shoumkh         region.vaddr = vaddr;
63c2481452Shoumkh         return region;
64c2481452Shoumkh     }
65c2481452Shoumkh 
66c2481452Shoumkh     /// @brief 将内存块归还给buddy
67c2481452Shoumkh     ///
68c2481452Shoumkh     /// @param vaddr 虚拟地址
69c2481452Shoumkh     ///
70c2481452Shoumkh     /// @param exp 内存空间的大小(2^exp)
71c2481452Shoumkh     ///
72c2481452Shoumkh     /// @param list_guard 【exp】对应的链表
73c2481452Shoumkh     ///
74c2481452Shoumkh     /// @return Ok(i32) 返回0
75c2481452Shoumkh     ///
76c2481452Shoumkh     /// @return Err(i32) 返回错误码
77*a7eb62a4Shoumkh     fn give_back_block(&self, vaddr: u64, exp: u32) -> Result<i32, i32> {
78c2481452Shoumkh         // 确保内存对齐,低位都要为0
79c2481452Shoumkh         if (vaddr & ((1 << exp) - 1)) != 0 {
80c2481452Shoumkh             return Err(-(EINVAL as i32));
81c2481452Shoumkh         }
82*a7eb62a4Shoumkh         let region: Box<MmioBuddyAddrRegion> = self.create_region(vaddr);
83c2481452Shoumkh         // 加入buddy
84c2481452Shoumkh         let list_guard: &mut SpinLockGuard<MmioFreeRegionList> =
85*a7eb62a4Shoumkh             &mut self.free_regions[exp2index(exp)].lock();
86*a7eb62a4Shoumkh         self.push_block(region, list_guard);
87c2481452Shoumkh         return Ok(0);
88c2481452Shoumkh     }
89c2481452Shoumkh 
90c2481452Shoumkh     /// @brief 将给定大小为2^{exp}的内存块一分为二,并插入内存块大小为2^{exp-1}的链表中
91c2481452Shoumkh     ///
92c2481452Shoumkh     /// @param region 要被分割的地址区域结构体(保证其已经从链表中取出)
93c2481452Shoumkh     ///
94c2481452Shoumkh     /// @param exp 要被分割的地址区域的大小的幂
95c2481452Shoumkh     ///
96c2481452Shoumkh     /// @param list_guard 【exp-1】对应的链表
97*a7eb62a4Shoumkh     fn split_block(
98c2481452Shoumkh         &self,
99c2481452Shoumkh         region: Box<MmioBuddyAddrRegion>,
100c2481452Shoumkh         exp: u32,
101c2481452Shoumkh         low_list_guard: &mut SpinLockGuard<MmioFreeRegionList>,
102c2481452Shoumkh     ) {
103*a7eb62a4Shoumkh         let vaddr: u64 = self.calculate_block_vaddr(region.vaddr, exp - 1);
104*a7eb62a4Shoumkh         let new_region: Box<MmioBuddyAddrRegion> = self.create_region(vaddr);
105*a7eb62a4Shoumkh         self.push_block(region, low_list_guard);
106*a7eb62a4Shoumkh         self.push_block(new_region, low_list_guard);
107c2481452Shoumkh     }
108c2481452Shoumkh 
109c2481452Shoumkh     /// @brief 从buddy中申请一块指定大小的内存区域
110c2481452Shoumkh     ///
111c2481452Shoumkh     /// @param exp 要申请的内存块的大小的幂(2^exp)
112c2481452Shoumkh     ///
113c2481452Shoumkh     /// @param list_guard exp对应的链表
114c2481452Shoumkh     ///
115c2481452Shoumkh     /// @return Ok(Box<MmioBuddyAddrRegion>) 符合要求的内存区域。
116c2481452Shoumkh     ///
117c2481452Shoumkh     /// @return Err(MmioResult)
118c2481452Shoumkh     /// - 没有满足要求的内存块时,返回ENOFOUND
119c2481452Shoumkh     /// - 申请的内存块大小超过合法范围,返回WRONGEXP
120c2481452Shoumkh     /// - 调用函数出错时,返回出错函数对应错误码
121*a7eb62a4Shoumkh     fn query_addr_region(
122c2481452Shoumkh         &self,
123c2481452Shoumkh         exp: u32,
124c2481452Shoumkh         list_guard: &mut SpinLockGuard<MmioFreeRegionList>,
125c2481452Shoumkh     ) -> Result<Box<MmioBuddyAddrRegion>, MmioResult> {
126c2481452Shoumkh         // 申请范围错误
127c2481452Shoumkh         if exp < MMIO_BUDDY_MIN_EXP || exp > MMIO_BUDDY_MAX_EXP {
128*a7eb62a4Shoumkh             kdebug!("query_addr_region: exp wrong");
129c2481452Shoumkh             return Err(MmioResult::WRONGEXP);
130c2481452Shoumkh         }
131c2481452Shoumkh         // 没有恰好符合要求的内存块
132c2481452Shoumkh         // 注意:exp对应的链表list_guard已上锁【注意避免死锁问题】
133c2481452Shoumkh         if list_guard.num_free == 0 {
134c2481452Shoumkh             // 找到最小符合申请范围的内存块
135c2481452Shoumkh             // 将大的内存块依次分成小块内存,直到能够满足exp大小,即将exp+1分成两块exp
136c2481452Shoumkh             for e in exp + 1..MMIO_BUDDY_MAX_EXP + 1 {
137*a7eb62a4Shoumkh                 if self.free_regions[exp2index(e) as usize].lock().num_free == 0 {
138c2481452Shoumkh                     continue;
139c2481452Shoumkh                 }
140c2481452Shoumkh                 for e2 in (exp + 1..e + 1).rev() {
141*a7eb62a4Shoumkh                     match self.pop_block(&mut self.free_regions[exp2index(e2) as usize].lock()) {
142c2481452Shoumkh                         Ok(region) => {
143c2481452Shoumkh                             if e2 != exp + 1 {
144c2481452Shoumkh                                 // 要将分裂后的内存块插入到更小的链表中
145c2481452Shoumkh                                 let low_list_guard: &mut SpinLockGuard<MmioFreeRegionList> =
146*a7eb62a4Shoumkh                                     &mut self.free_regions[exp2index(e2 - 1) as usize].lock();
147*a7eb62a4Shoumkh                                 self.split_block(region, e2, low_list_guard);
148c2481452Shoumkh                             } else {
149c2481452Shoumkh                                 // 由于exp对应的链表list_guard已经被锁住了 不能再加锁
150c2481452Shoumkh                                 // 所以直接将list_guard传入
151*a7eb62a4Shoumkh                                 self.split_block(region, e2, list_guard);
152c2481452Shoumkh                             }
153c2481452Shoumkh                         }
154c2481452Shoumkh                         Err(err) => {
155c2481452Shoumkh                             kdebug!("buddy_pop_region get wrong");
156c2481452Shoumkh                             return Err(err);
157c2481452Shoumkh                         }
158c2481452Shoumkh                     }
159c2481452Shoumkh                 }
160c2481452Shoumkh                 break;
161c2481452Shoumkh             }
162c2481452Shoumkh             // 判断是否获得了exp大小的内存块
163c2481452Shoumkh             if list_guard.num_free > 0 {
164c2481452Shoumkh                 return Ok(list_guard.list.pop_back().unwrap());
165c2481452Shoumkh             }
166c2481452Shoumkh             // 拆分大内存块无法获得exp大小内存块
167c2481452Shoumkh             // 尝试用小内存块合成
168c2481452Shoumkh             // 即将两块exp合成一块exp+1
169c2481452Shoumkh             for e in MMIO_BUDDY_MIN_EXP..exp {
170c2481452Shoumkh                 if e != exp - 1 {
171c2481452Shoumkh                     let high_list_guard: &mut SpinLockGuard<MmioFreeRegionList> =
172*a7eb62a4Shoumkh                         &mut self.free_regions[exp2index(exp + 1)].lock();
173*a7eb62a4Shoumkh                     match self.merge_all_exp(
174c2481452Shoumkh                         e,
175*a7eb62a4Shoumkh                         &mut self.free_regions[exp2index(e) as usize].lock(),
176c2481452Shoumkh                         high_list_guard,
177c2481452Shoumkh                     ) {
178c2481452Shoumkh                         Ok(_) => continue,
179c2481452Shoumkh                         Err(err) => {
180c2481452Shoumkh                             return Err(err);
181c2481452Shoumkh                         }
182c2481452Shoumkh                     }
183c2481452Shoumkh                 } else {
184*a7eb62a4Shoumkh                     match self.merge_all_exp(
185c2481452Shoumkh                         e,
186*a7eb62a4Shoumkh                         &mut self.free_regions[exp2index(e) as usize].lock(),
187c2481452Shoumkh                         list_guard,
188c2481452Shoumkh                     ) {
189c2481452Shoumkh                         Ok(_) => continue,
190c2481452Shoumkh                         Err(err) => {
191c2481452Shoumkh                             return Err(err);
192c2481452Shoumkh                         }
193c2481452Shoumkh                     }
194c2481452Shoumkh                 }
195c2481452Shoumkh             }
196c2481452Shoumkh 
197c2481452Shoumkh             //判断是否获得了exp大小的内存块
198c2481452Shoumkh             if list_guard.num_free > 0 {
199c2481452Shoumkh                 return Ok(list_guard.list.pop_back().unwrap());
200c2481452Shoumkh             }
201c2481452Shoumkh             return Err(MmioResult::ENOFOUND);
202c2481452Shoumkh         } else {
203c2481452Shoumkh             return Ok(list_guard.list.pop_back().unwrap());
204c2481452Shoumkh         }
205c2481452Shoumkh     }
206c2481452Shoumkh 
207c2481452Shoumkh     /// @brief 对query_addr_region进行封装
208c2481452Shoumkh     ///
209c2481452Shoumkh     /// @param exp 内存区域的大小(2^exp)
210c2481452Shoumkh     ///
211c2481452Shoumkh     /// @return Ok(Box<MmioBuddyAddrRegion>)符合要求的内存块信息结构体。
212c2481452Shoumkh     /// @return Err(MmioResult) 没有满足要求的内存块时,返回__query_addr_region的错误码。
213c2481452Shoumkh     fn mmio_buddy_query_addr_region(
214c2481452Shoumkh         &self,
215c2481452Shoumkh         exp: u32,
216c2481452Shoumkh     ) -> Result<Box<MmioBuddyAddrRegion>, MmioResult> {
217c2481452Shoumkh         let list_guard: &mut SpinLockGuard<MmioFreeRegionList> =
218*a7eb62a4Shoumkh             &mut self.free_regions[exp2index(exp)].lock();
219*a7eb62a4Shoumkh         match self.query_addr_region(exp, list_guard) {
220c2481452Shoumkh             Ok(ret) => return Ok(ret),
221c2481452Shoumkh             Err(err) => {
222c2481452Shoumkh                 kdebug!("mmio_buddy_query_addr_region failed");
223c2481452Shoumkh                 return Err(err);
224c2481452Shoumkh             }
225c2481452Shoumkh         }
226c2481452Shoumkh     }
227c2481452Shoumkh     /// @brief 往指定的地址空间链表中添加一个地址区域
228c2481452Shoumkh     ///
229c2481452Shoumkh     /// @param region 要被添加的地址结构体
230c2481452Shoumkh     ///
231c2481452Shoumkh     /// @param list_guard 目标链表
232*a7eb62a4Shoumkh     fn push_block(
233c2481452Shoumkh         &self,
234c2481452Shoumkh         region: Box<MmioBuddyAddrRegion>,
235c2481452Shoumkh         list_guard: &mut SpinLockGuard<MmioFreeRegionList>,
236c2481452Shoumkh     ) {
237c2481452Shoumkh         list_guard.list.push_back(region);
238c2481452Shoumkh         list_guard.num_free += 1;
239c2481452Shoumkh     }
240c2481452Shoumkh 
241c2481452Shoumkh     /// @brief 根据地址和内存块大小,计算伙伴块虚拟内存的地址
242c2481452Shoumkh     #[inline(always)]
243*a7eb62a4Shoumkh     fn calculate_block_vaddr(&self, vaddr: u64, exp: u32) -> u64 {
244c2481452Shoumkh         return vaddr ^ (1 << exp);
245c2481452Shoumkh     }
246c2481452Shoumkh 
247c2481452Shoumkh     /// @brief 寻找并弹出指定内存块的伙伴块
248c2481452Shoumkh     ///
249c2481452Shoumkh     /// @param region 对应内存块的信息
250c2481452Shoumkh     ///
251c2481452Shoumkh     /// @param exp 内存块大小
252c2481452Shoumkh     ///
253c2481452Shoumkh     /// @param list_guard 【exp】对应的链表
254c2481452Shoumkh     ///
255c2481452Shoumkh     /// @return Ok(Box<MmioBuddyAddrRegion) 返回伙伴块的引用
256c2481452Shoumkh     /// @return Err(MmioResult)
257c2481452Shoumkh     /// - 当链表为空,返回ISEMPTY
258c2481452Shoumkh     /// - 没有找到伙伴块,返回ENOFOUND
259*a7eb62a4Shoumkh     fn pop_buddy_block(
260c2481452Shoumkh         &self,
261c2481452Shoumkh         vaddr: u64,
262c2481452Shoumkh         exp: u32,
263c2481452Shoumkh         list_guard: &mut SpinLockGuard<MmioFreeRegionList>,
264c2481452Shoumkh     ) -> Result<Box<MmioBuddyAddrRegion>, MmioResult> {
265c2481452Shoumkh         if list_guard.list.len() == 0 {
266c2481452Shoumkh             return Err(MmioResult::ISEMPTY);
267c2481452Shoumkh         } else {
268c2481452Shoumkh             //计算伙伴块的地址
269*a7eb62a4Shoumkh             let buddy_vaddr = self.calculate_block_vaddr(vaddr, exp);
270c2481452Shoumkh 
271c2481452Shoumkh             // element 只会有一个元素
272c2481452Shoumkh             let mut element: Vec<Box<MmioBuddyAddrRegion>> = list_guard
273c2481452Shoumkh                 .list
274c2481452Shoumkh                 .drain_filter(|x| x.vaddr == buddy_vaddr)
275c2481452Shoumkh                 .collect();
276c2481452Shoumkh             if element.len() == 1 {
277c2481452Shoumkh                 list_guard.num_free -= 1;
278c2481452Shoumkh                 return Ok(element.pop().unwrap());
279c2481452Shoumkh             }
280c2481452Shoumkh 
281c2481452Shoumkh             //没有找到对应的伙伴块
282c2481452Shoumkh             return Err(MmioResult::ENOFOUND);
283c2481452Shoumkh         }
284c2481452Shoumkh     }
285c2481452Shoumkh 
286c2481452Shoumkh     /// @brief 从指定空闲链表中取出内存区域
287c2481452Shoumkh     ///
288c2481452Shoumkh     /// @param list_guard 【exp】对应的链表
289c2481452Shoumkh     ///
290c2481452Shoumkh     /// @return Ok(Box<MmioBuddyAddrRegion>) 内存块信息结构体的引用。
291c2481452Shoumkh     ///
292c2481452Shoumkh     /// @return Err(MmioResult) 当链表为空,无法删除时,返回ISEMPTY
293*a7eb62a4Shoumkh     fn pop_block(
294c2481452Shoumkh         &self,
295c2481452Shoumkh         list_guard: &mut SpinLockGuard<MmioFreeRegionList>,
296c2481452Shoumkh     ) -> Result<Box<MmioBuddyAddrRegion>, MmioResult> {
297c2481452Shoumkh         if !list_guard.list.is_empty() {
298c2481452Shoumkh             list_guard.num_free -= 1;
299c2481452Shoumkh             return Ok(list_guard.list.pop_back().unwrap());
300c2481452Shoumkh         }
301c2481452Shoumkh         return Err(MmioResult::ISEMPTY);
302c2481452Shoumkh     }
303c2481452Shoumkh 
304c2481452Shoumkh     /// @brief 合并所有2^{exp}大小的内存块
305c2481452Shoumkh     ///
306c2481452Shoumkh     /// @param exp 内存块大小的幂(2^exp)
307c2481452Shoumkh     ///
308c2481452Shoumkh     /// @param list_guard exp对应的链表
309c2481452Shoumkh     ///
310c2481452Shoumkh     /// @param high_list_guard exp+1对应的链表
311c2481452Shoumkh     ///
312c2481452Shoumkh     /// @return Ok(MmioResult) 合并成功返回SUCCESS
313c2481452Shoumkh     /// @return Err(MmioResult)
314c2481452Shoumkh     /// - 内存块过少,无法合并,返回EINVAL
315*a7eb62a4Shoumkh     /// - pop_buddy_block调用出错,返回其错误码
316*a7eb62a4Shoumkh     /// - merge_blocks调用出错,返回其错误码
317*a7eb62a4Shoumkh     fn merge_all_exp(
318c2481452Shoumkh         &self,
319c2481452Shoumkh         exp: u32,
320c2481452Shoumkh         list_guard: &mut SpinLockGuard<MmioFreeRegionList>,
321c2481452Shoumkh         high_list_guard: &mut SpinLockGuard<MmioFreeRegionList>,
322c2481452Shoumkh     ) -> Result<MmioResult, MmioResult> {
323c2481452Shoumkh         // 至少要两个内存块才能合并
324c2481452Shoumkh         if list_guard.num_free <= 1 {
325c2481452Shoumkh             return Err(MmioResult::EINVAL);
326c2481452Shoumkh         }
327c2481452Shoumkh         loop {
328c2481452Shoumkh             if list_guard.num_free <= 1 {
329c2481452Shoumkh                 break;
330c2481452Shoumkh             }
331c2481452Shoumkh             // 获取内存块
332c2481452Shoumkh             let vaddr: u64 = list_guard.list.back().unwrap().vaddr;
333c2481452Shoumkh             // 获取伙伴内存块
334*a7eb62a4Shoumkh             match self.pop_buddy_block(vaddr, exp, list_guard) {
335c2481452Shoumkh                 Err(err) => {
336c2481452Shoumkh                     return Err(err);
337c2481452Shoumkh                 }
338c2481452Shoumkh                 Ok(buddy_region) => {
339c2481452Shoumkh                     let region: Box<MmioBuddyAddrRegion> = list_guard.list.pop_back().unwrap();
340c2481452Shoumkh                     let copy_region: Box<MmioBuddyAddrRegion> = Box::new(MmioBuddyAddrRegion {
341c2481452Shoumkh                         vaddr: region.vaddr,
342c2481452Shoumkh                     });
343c2481452Shoumkh                     // 在两块内存都被取出之后才进行合并
344*a7eb62a4Shoumkh                     match self.merge_blocks(region, buddy_region, exp, high_list_guard) {
345c2481452Shoumkh                         Err(err) => {
346c2481452Shoumkh                             // 如果合并失败了要将取出来的元素放回去
347*a7eb62a4Shoumkh                             self.push_block(copy_region, list_guard);
348*a7eb62a4Shoumkh                             kdebug!("merge_all_exp: merge_blocks failed");
349c2481452Shoumkh                             return Err(err);
350c2481452Shoumkh                         }
351c2481452Shoumkh                         Ok(_) => continue,
352c2481452Shoumkh                     }
353c2481452Shoumkh                 }
354c2481452Shoumkh             }
355c2481452Shoumkh         }
356c2481452Shoumkh         return Ok(MmioResult::SUCCESS);
357c2481452Shoumkh     }
358c2481452Shoumkh 
359c2481452Shoumkh     /// @brief 合并两个【已经从链表中取出】的内存块
360c2481452Shoumkh     ///
361c2481452Shoumkh     /// @param region_1 第一个内存块
362c2481452Shoumkh     ///
363c2481452Shoumkh     /// @param region_2 第二个内存
364c2481452Shoumkh     ///
365c2481452Shoumkh     /// @return Ok(MmioResult) 成功返回SUCCESS
366c2481452Shoumkh     ///
367c2481452Shoumkh     /// @return Err(MmioResult) 两个内存块不是伙伴块,返回EINVAL
368*a7eb62a4Shoumkh     fn merge_blocks(
369c2481452Shoumkh         &self,
370c2481452Shoumkh         region_1: Box<MmioBuddyAddrRegion>,
371c2481452Shoumkh         region_2: Box<MmioBuddyAddrRegion>,
372c2481452Shoumkh         exp: u32,
373c2481452Shoumkh         high_list_guard: &mut SpinLockGuard<MmioFreeRegionList>,
374c2481452Shoumkh     ) -> Result<MmioResult, MmioResult> {
375c2481452Shoumkh         // 判断是否为伙伴块
376*a7eb62a4Shoumkh         if region_1.vaddr != self.calculate_block_vaddr(region_2.vaddr, exp) {
377c2481452Shoumkh             return Err(MmioResult::EINVAL);
378c2481452Shoumkh         }
379c2481452Shoumkh         // 将大的块放进下一级链表
380*a7eb62a4Shoumkh         self.push_block(region_1, high_list_guard);
381c2481452Shoumkh         return Ok(MmioResult::SUCCESS);
382c2481452Shoumkh     }
383c2481452Shoumkh 
384c2481452Shoumkh     /// @brief 创建一块mmio区域,并将vma绑定到initial_mm
385c2481452Shoumkh     ///
386c2481452Shoumkh     /// @param size mmio区域的大小(字节)
387c2481452Shoumkh     ///
388c2481452Shoumkh     /// @param vm_flags 要把vma设置成的标志
389c2481452Shoumkh     ///
390c2481452Shoumkh     /// @param res_vaddr 返回值-分配得到的虚拟地址
391c2481452Shoumkh     ///
392c2481452Shoumkh     /// @param res_length 返回值-分配的虚拟地址空间长度
393c2481452Shoumkh     ///
394*a7eb62a4Shoumkh     /// @return Ok(i32) 成功返回0
395*a7eb62a4Shoumkh     ///
396*a7eb62a4Shoumkh     /// @return Err(i32) 失败返回错误码
397*a7eb62a4Shoumkh     fn create_mmio(
398*a7eb62a4Shoumkh         &self,
399c2481452Shoumkh         size: u32,
400c2481452Shoumkh         vm_flags: vm_flags_t,
401c2481452Shoumkh         res_vaddr: *mut u64,
402c2481452Shoumkh         res_length: *mut u64,
403*a7eb62a4Shoumkh     ) -> Result<i32, i32> {
404c2481452Shoumkh         if size > PAGE_1G_SIZE || size == 0 {
405*a7eb62a4Shoumkh             return Err(-(EPERM as i32));
406c2481452Shoumkh         }
407c2481452Shoumkh         let mut retval: i32 = 0;
408c2481452Shoumkh         // 计算前导0
409c2481452Shoumkh         let mut size_exp: u32 = 31 - size.leading_zeros();
410c2481452Shoumkh         // 记录最终申请的空间大小
411c2481452Shoumkh         let mut new_size: u32 = size;
412c2481452Shoumkh         // 对齐要申请的空间大小
413c2481452Shoumkh         // 如果要申请的空间大小小于4k,则分配4k
414c2481452Shoumkh         if size_exp < PAGE_4K_SHIFT {
415c2481452Shoumkh             new_size = PAGE_4K_SIZE;
416c2481452Shoumkh             size_exp = PAGE_4K_SHIFT;
417c2481452Shoumkh         } else if (new_size & (!(1 << size_exp))) != 0 {
418c2481452Shoumkh             // 向左对齐空间大小
419c2481452Shoumkh             size_exp += 1;
420c2481452Shoumkh             new_size = 1 << size_exp;
421c2481452Shoumkh         }
422c2481452Shoumkh         match MMIO_POOL.mmio_buddy_query_addr_region(size_exp) {
423c2481452Shoumkh             Ok(region) => {
424c2481452Shoumkh                 unsafe {
425c2481452Shoumkh                     *res_vaddr = region.vaddr;
426c2481452Shoumkh                     *res_length = new_size as u64;
427c2481452Shoumkh                 }
428c2481452Shoumkh                 // 创建vma
429c2481452Shoumkh                 let flags: u64 = vm_flags | (VM_IO | VM_DONTCOPY) as u64;
430c2481452Shoumkh                 let len_4k: u64 = (new_size % PAGE_2M_SIZE) as u64;
431c2481452Shoumkh                 let len_2m: u64 = new_size as u64 - len_4k;
432c2481452Shoumkh                 let mut loop_i: u64 = 0;
433c2481452Shoumkh                 // 先分配2M的vma
434c2481452Shoumkh                 loop {
435c2481452Shoumkh                     if loop_i >= len_2m {
436c2481452Shoumkh                         break;
437c2481452Shoumkh                     }
438c2481452Shoumkh                     let vma: *mut *mut vm_area_struct = null_mut();
439c2481452Shoumkh                     retval = unsafe {
440c2481452Shoumkh                         mm_create_vma(
441c2481452Shoumkh                             &mut initial_mm,
442c2481452Shoumkh                             region.vaddr + loop_i,
443c2481452Shoumkh                             PAGE_2M_SIZE.into(),
444c2481452Shoumkh                             flags,
445c2481452Shoumkh                             null_mut(),
446c2481452Shoumkh                             vma,
447c2481452Shoumkh                         )
448c2481452Shoumkh                     };
449c2481452Shoumkh                     if retval != 0 {
450c2481452Shoumkh                         kdebug!(
451c2481452Shoumkh                             "failed to create mmio 2m vma. pid = {:?}",
452c2481452Shoumkh                             current_pcb().pid
453c2481452Shoumkh                         );
454c2481452Shoumkh                         unsafe {
455c2481452Shoumkh                             vm_area_del(*vma);
456c2481452Shoumkh                             vm_area_free(*vma);
457c2481452Shoumkh                         }
458*a7eb62a4Shoumkh                         return Err(retval);
459c2481452Shoumkh                     }
460c2481452Shoumkh                     loop_i += PAGE_2M_SIZE as u64;
461c2481452Shoumkh                 }
462c2481452Shoumkh                 // 分配4K的vma
463c2481452Shoumkh                 loop_i = len_2m;
464c2481452Shoumkh                 loop {
465c2481452Shoumkh                     if loop_i >= size as u64 {
466c2481452Shoumkh                         break;
467c2481452Shoumkh                     }
468c2481452Shoumkh                     let vma: *mut *mut vm_area_struct = null_mut();
469c2481452Shoumkh                     retval = unsafe {
470c2481452Shoumkh                         mm_create_vma(
471c2481452Shoumkh                             &mut initial_mm,
472c2481452Shoumkh                             region.vaddr + loop_i,
473c2481452Shoumkh                             PAGE_4K_SIZE.into(),
474c2481452Shoumkh                             flags,
475c2481452Shoumkh                             null_mut(),
476c2481452Shoumkh                             vma,
477c2481452Shoumkh                         )
478c2481452Shoumkh                     };
479c2481452Shoumkh                     if retval != 0 {
480c2481452Shoumkh                         kdebug!(
481c2481452Shoumkh                             "failed to create mmio 4k vma. pid = {:?}",
482c2481452Shoumkh                             current_pcb().pid
483c2481452Shoumkh                         );
484c2481452Shoumkh                         unsafe {
485c2481452Shoumkh                             vm_area_del(*vma);
486c2481452Shoumkh                             vm_area_free(*vma);
487c2481452Shoumkh                         }
488*a7eb62a4Shoumkh                         return Err(retval);
489c2481452Shoumkh                     }
490c2481452Shoumkh                     loop_i += PAGE_4K_SIZE as u64;
491c2481452Shoumkh                 }
492c2481452Shoumkh             }
493c2481452Shoumkh             Err(_) => {
494c2481452Shoumkh                 kdebug!("failed to create mmio vma.pid = {:?}", current_pcb().pid);
495*a7eb62a4Shoumkh                 return Err(-(ENOMEM as i32));
496c2481452Shoumkh             }
497c2481452Shoumkh         }
498*a7eb62a4Shoumkh         return Ok(retval);
499c2481452Shoumkh     }
500c2481452Shoumkh 
501c2481452Shoumkh     /// @brief 取消mmio的映射并将地址空间归还到buddy中
502c2481452Shoumkh     ///
503c2481452Shoumkh     /// @param vaddr 起始的虚拟地址
504c2481452Shoumkh     ///
505c2481452Shoumkh     /// @param length 要归还的地址空间的长度
506c2481452Shoumkh     ///
507c2481452Shoumkh     /// @return Ok(i32) 成功返回0
508c2481452Shoumkh     ///
509c2481452Shoumkh     /// @return Err(i32) 失败返回错误码
510*a7eb62a4Shoumkh     fn release_mmio(&self, vaddr: u64, length: u64) -> Result<i32, i32> {
511c2481452Shoumkh         //先将要释放的空间取消映射
512c2481452Shoumkh         unsafe {
513c2481452Shoumkh             mm_unmap(&mut initial_mm, vaddr, length, false);
514c2481452Shoumkh         }
515c2481452Shoumkh         let mut loop_i: u64 = 0;
516c2481452Shoumkh         loop {
517c2481452Shoumkh             if loop_i >= length {
518c2481452Shoumkh                 break;
519c2481452Shoumkh             }
520c2481452Shoumkh             // 获取要释放的vma的结构体
521c2481452Shoumkh             let vma: *mut vm_area_struct = unsafe { vma_find(&mut initial_mm, vaddr + loop_i) };
522c2481452Shoumkh             if vma == null_mut() {
523c2481452Shoumkh                 kdebug!(
524c2481452Shoumkh                     "mmio_release failed: vma not found. At address: {:?}, pid = {:?}",
525c2481452Shoumkh                     vaddr + loop_i,
526c2481452Shoumkh                     current_pcb().pid
527c2481452Shoumkh                 );
528*a7eb62a4Shoumkh                 return Err(-(EINVAL as i32));
529c2481452Shoumkh             }
530c2481452Shoumkh             // 检查vma起始地址是否正确
531c2481452Shoumkh             if unsafe { (*vma).vm_start != (vaddr + loop_i) } {
532c2481452Shoumkh                 kdebug!(
533c2481452Shoumkh                     "mmio_release failed: addr_start is not equal to current: {:?}. pid = {:?}",
534c2481452Shoumkh                     vaddr + loop_i,
535c2481452Shoumkh                     current_pcb().pid
536c2481452Shoumkh                 );
537*a7eb62a4Shoumkh                 return Err(-(EINVAL as i32));
538c2481452Shoumkh             }
539c2481452Shoumkh             // 将vma对应空间归还
540*a7eb62a4Shoumkh             match MMIO_POOL.give_back_block(unsafe { (*vma).vm_start }, unsafe {
541c2481452Shoumkh                 31 - ((*vma).vm_end - (*vma).vm_start).leading_zeros()
542c2481452Shoumkh             }) {
543c2481452Shoumkh                 Ok(_) => {
544c2481452Shoumkh                     loop_i += unsafe { (*vma).vm_end - (*vma).vm_start };
545c2481452Shoumkh                     unsafe {
546c2481452Shoumkh                         vm_area_del(vma);
547c2481452Shoumkh                         vm_area_free(vma);
548c2481452Shoumkh                     }
549c2481452Shoumkh                 }
550c2481452Shoumkh                 Err(err) => {
551c2481452Shoumkh                     // vma对应空间没有成功归还的话,就不删除vma
552c2481452Shoumkh                     kdebug!(
553c2481452Shoumkh                         "mmio_release give_back failed: pid = {:?}",
554c2481452Shoumkh                         current_pcb().pid
555c2481452Shoumkh                     );
556*a7eb62a4Shoumkh                     return Err(err);
557*a7eb62a4Shoumkh                 }
558*a7eb62a4Shoumkh             }
559*a7eb62a4Shoumkh         }
560*a7eb62a4Shoumkh         return Ok(0);
561*a7eb62a4Shoumkh     }
562*a7eb62a4Shoumkh }
563*a7eb62a4Shoumkh 
564*a7eb62a4Shoumkh /// @brief mmio伙伴系统内部的地址区域结构体
565*a7eb62a4Shoumkh pub struct MmioBuddyAddrRegion {
566*a7eb62a4Shoumkh     vaddr: u64,
567*a7eb62a4Shoumkh }
568*a7eb62a4Shoumkh impl MmioBuddyAddrRegion {
569*a7eb62a4Shoumkh     pub fn new() -> Self {
570*a7eb62a4Shoumkh         return MmioBuddyAddrRegion {
571*a7eb62a4Shoumkh             ..Default::default()
572*a7eb62a4Shoumkh         };
573*a7eb62a4Shoumkh     }
574*a7eb62a4Shoumkh }
575*a7eb62a4Shoumkh impl Default for MmioBuddyAddrRegion {
576*a7eb62a4Shoumkh     fn default() -> Self {
577*a7eb62a4Shoumkh         MmioBuddyAddrRegion {
578*a7eb62a4Shoumkh             vaddr: Default::default(),
579*a7eb62a4Shoumkh         }
580*a7eb62a4Shoumkh     }
581*a7eb62a4Shoumkh }
582*a7eb62a4Shoumkh 
583*a7eb62a4Shoumkh /// @brief 空闲页数组结构体
584*a7eb62a4Shoumkh pub struct MmioFreeRegionList {
585*a7eb62a4Shoumkh     /// 存储mmio_buddy的地址链表
586*a7eb62a4Shoumkh     list: LinkedList<Box<MmioBuddyAddrRegion>>,
587*a7eb62a4Shoumkh     /// 空闲块的数量
588*a7eb62a4Shoumkh     num_free: i64,
589*a7eb62a4Shoumkh }
590*a7eb62a4Shoumkh impl MmioFreeRegionList {
591*a7eb62a4Shoumkh     fn new() -> Self {
592*a7eb62a4Shoumkh         return MmioFreeRegionList {
593*a7eb62a4Shoumkh             ..Default::default()
594*a7eb62a4Shoumkh         };
595*a7eb62a4Shoumkh     }
596*a7eb62a4Shoumkh }
597*a7eb62a4Shoumkh impl Default for MmioFreeRegionList {
598*a7eb62a4Shoumkh     fn default() -> Self {
599*a7eb62a4Shoumkh         MmioFreeRegionList {
600*a7eb62a4Shoumkh             list: Default::default(),
601*a7eb62a4Shoumkh             num_free: 0,
602*a7eb62a4Shoumkh         }
603*a7eb62a4Shoumkh     }
604*a7eb62a4Shoumkh }
605*a7eb62a4Shoumkh 
606*a7eb62a4Shoumkh /// @brief 初始化mmio的伙伴系统
607*a7eb62a4Shoumkh #[no_mangle]
608*a7eb62a4Shoumkh pub extern "C" fn __mmio_buddy_init() {
609*a7eb62a4Shoumkh     // 创建一堆1GB的地址块
610*a7eb62a4Shoumkh     let cnt_1g_blocks: u32 = ((MMIO_TOP - MMIO_BASE) / PAGE_1G_SIZE as i64) as u32;
611*a7eb62a4Shoumkh     let mut vaddr_base: u64 = MMIO_BASE as u64;
612*a7eb62a4Shoumkh     for _ in 0..cnt_1g_blocks {
613*a7eb62a4Shoumkh         match MMIO_POOL.give_back_block(vaddr_base, PAGE_1G_SHIFT) {
614*a7eb62a4Shoumkh             Ok(_) => {
615*a7eb62a4Shoumkh                 vaddr_base += PAGE_1G_SIZE as u64;
616*a7eb62a4Shoumkh             }
617*a7eb62a4Shoumkh             Err(_) => {
618*a7eb62a4Shoumkh                 kerror!("__mmio_buddy_init failed");
619*a7eb62a4Shoumkh                 return;
620*a7eb62a4Shoumkh             }
621*a7eb62a4Shoumkh         }
622*a7eb62a4Shoumkh     }
623*a7eb62a4Shoumkh }
624*a7eb62a4Shoumkh 
625*a7eb62a4Shoumkh /// @brief 将内存对象大小的幂转换成内存池中的数组的下标
626*a7eb62a4Shoumkh ///
627*a7eb62a4Shoumkh /// @param exp内存大小
628*a7eb62a4Shoumkh ///
629*a7eb62a4Shoumkh /// @return 内存池数组下标
630*a7eb62a4Shoumkh #[inline(always)]
631*a7eb62a4Shoumkh fn exp2index(exp: u32) -> usize {
632*a7eb62a4Shoumkh     return (exp - 12) as usize;
633*a7eb62a4Shoumkh }
634*a7eb62a4Shoumkh 
635*a7eb62a4Shoumkh /// @brief 创建一块mmio区域,并将vma绑定到initial_mm
636*a7eb62a4Shoumkh ///
637*a7eb62a4Shoumkh /// @param size mmio区域的大小(字节)
638*a7eb62a4Shoumkh ///
639*a7eb62a4Shoumkh /// @param vm_flags 要把vma设置成的标志
640*a7eb62a4Shoumkh ///
641*a7eb62a4Shoumkh /// @param res_vaddr 返回值-分配得到的虚拟地址
642*a7eb62a4Shoumkh ///
643*a7eb62a4Shoumkh /// @param res_length 返回值-分配的虚拟地址空间长度
644*a7eb62a4Shoumkh ///
645*a7eb62a4Shoumkh /// @return int 错误码
646*a7eb62a4Shoumkh #[no_mangle]
647*a7eb62a4Shoumkh pub extern "C" fn mmio_create(
648*a7eb62a4Shoumkh     size: u32,
649*a7eb62a4Shoumkh     vm_flags: vm_flags_t,
650*a7eb62a4Shoumkh     res_vaddr: *mut u64,
651*a7eb62a4Shoumkh     res_length: *mut u64,
652*a7eb62a4Shoumkh ) -> i32 {
653*a7eb62a4Shoumkh     if let Err(err) = MMIO_POOL.create_mmio(size, vm_flags, res_vaddr, res_length) {
654c2481452Shoumkh         return err;
655*a7eb62a4Shoumkh     } else {
656c2481452Shoumkh         return 0;
657c2481452Shoumkh     }
658*a7eb62a4Shoumkh }
659*a7eb62a4Shoumkh 
660*a7eb62a4Shoumkh /// @brief 取消mmio的映射并将地址空间归还到buddy中
661*a7eb62a4Shoumkh ///
662*a7eb62a4Shoumkh /// @param vaddr 起始的虚拟地址
663*a7eb62a4Shoumkh ///
664*a7eb62a4Shoumkh /// @param length 要归还的地址空间的长度
665*a7eb62a4Shoumkh ///
666*a7eb62a4Shoumkh /// @return Ok(i32) 成功返回0
667*a7eb62a4Shoumkh ///
668*a7eb62a4Shoumkh /// @return Err(i32) 失败返回错误码
669*a7eb62a4Shoumkh #[no_mangle]
670*a7eb62a4Shoumkh pub extern "C" fn mmio_release(vaddr: u64, length: u64) -> i32 {
671*a7eb62a4Shoumkh     if let Err(err) = MMIO_POOL.release_mmio(vaddr, length) {
672*a7eb62a4Shoumkh         return err;
673*a7eb62a4Shoumkh     } else {
674*a7eb62a4Shoumkh         return 0;
675*a7eb62a4Shoumkh     }
676*a7eb62a4Shoumkh }
677