-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathalloc.rs
1652 lines (1353 loc) · 46 KB
/
alloc.rs
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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: MIT OR Apache-2.0
//
// Copyright (c) 2022-2023 SUSE LLC
//
// Author: Joerg Roedel <jroedel@suse.de>
use crate::address::{Address, PhysAddr, VirtAddr};
use crate::error::SvsmError;
use crate::locking::SpinLock;
use crate::mm::virt_to_phys;
use crate::types::{PAGE_SHIFT, PAGE_SIZE};
use crate::utils::{align_up, zero_mem_region};
use core::alloc::{GlobalAlloc, Layout};
use core::mem::size_of;
use core::ptr;
use log;
// Support allocations up to order-5 (128kb)
pub const MAX_ORDER: usize = 6;
pub fn get_order(size: usize) -> usize {
(size
.checked_next_power_of_two()
.map_or(usize::BITS, usize::ilog2) as usize)
.saturating_sub(PAGE_SHIFT)
}
#[derive(Clone, Copy, Debug)]
#[repr(u64)]
enum PageType {
Free = 0,
Allocated = 1,
SlabPage = 2,
Compound = 3,
// File pages used for file and task data
File = 4,
Reserved = (1u64 << PageStorageType::TYPE_SHIFT) - 1,
}
impl TryFrom<u64> for PageType {
type Error = SvsmError;
fn try_from(val: u64) -> Result<Self, Self::Error> {
match val {
v if v == Self::Free as u64 => Ok(Self::Free),
v if v == Self::Allocated as u64 => Ok(Self::Allocated),
v if v == Self::SlabPage as u64 => Ok(Self::SlabPage),
v if v == Self::Compound as u64 => Ok(Self::Compound),
v if v == Self::File as u64 => Ok(Self::File),
v if v == Self::Reserved as u64 => Ok(Self::Reserved),
_ => Err(SvsmError::Mem),
}
}
}
#[derive(Clone, Copy, Debug)]
#[repr(transparent)]
struct PageStorageType(u64);
impl PageStorageType {
const TYPE_SHIFT: u64 = 4;
const TYPE_MASK: u64 = (1u64 << Self::TYPE_SHIFT) - 1;
const NEXT_SHIFT: u64 = 12;
const NEXT_MASK: u64 = !((1u64 << Self::NEXT_SHIFT) - 1);
const ORDER_MASK: u64 = (1u64 << (Self::NEXT_SHIFT - Self::TYPE_SHIFT)) - 1;
// SLAB pages are always order-0
const SLAB_MASK: u64 = !Self::TYPE_MASK;
const fn new(t: PageType) -> Self {
Self(t as u64)
}
fn encode_order(self, order: usize) -> Self {
Self(self.0 | ((order as u64) & Self::ORDER_MASK) << Self::TYPE_SHIFT)
}
fn encode_next(self, next_page: usize) -> Self {
Self(self.0 | (next_page as u64) << Self::NEXT_SHIFT)
}
fn encode_slab(self, slab: VirtAddr) -> Self {
Self(self.0 | (slab.bits() as u64) & Self::SLAB_MASK)
}
fn encode_refcount(self, refcount: u64) -> Self {
Self(self.0 | refcount << Self::TYPE_SHIFT)
}
fn decode_order(&self) -> usize {
((self.0 >> Self::TYPE_SHIFT) & Self::ORDER_MASK) as usize
}
fn decode_next(&self) -> usize {
((self.0 & Self::NEXT_MASK) >> Self::NEXT_SHIFT) as usize
}
fn decode_slab(&self) -> VirtAddr {
VirtAddr::from(self.0 & Self::SLAB_MASK)
}
fn decode_refcount(&self) -> u64 {
self.0 >> Self::TYPE_SHIFT
}
fn page_type(&self) -> Result<PageType, SvsmError> {
PageType::try_from(self.0 & Self::TYPE_MASK)
}
}
struct FreeInfo {
next_page: usize,
order: usize,
}
impl FreeInfo {
fn encode(&self) -> PageStorageType {
PageStorageType::new(PageType::Free)
.encode_order(self.order)
.encode_next(self.next_page)
}
fn decode(mem: PageStorageType) -> Self {
let next_page = mem.decode_next();
let order = mem.decode_order();
Self { next_page, order }
}
}
struct AllocatedInfo {
order: usize,
}
impl AllocatedInfo {
fn encode(&self) -> PageStorageType {
PageStorageType::new(PageType::Allocated).encode_order(self.order)
}
fn decode(mem: PageStorageType) -> Self {
let order = mem.decode_order();
AllocatedInfo { order }
}
}
struct SlabPageInfo {
slab: VirtAddr,
}
impl SlabPageInfo {
fn encode(&self) -> PageStorageType {
PageStorageType::new(PageType::SlabPage).encode_slab(self.slab)
}
fn decode(mem: PageStorageType) -> Self {
let slab = mem.decode_slab();
Self { slab }
}
}
struct CompoundInfo {
order: usize,
}
impl CompoundInfo {
fn encode(&self) -> PageStorageType {
PageStorageType::new(PageType::Compound).encode_order(self.order)
}
fn decode(mem: PageStorageType) -> Self {
let order = mem.decode_order();
Self { order }
}
}
struct ReservedInfo {}
impl ReservedInfo {
fn encode(&self) -> PageStorageType {
PageStorageType::new(PageType::Reserved)
}
fn decode(_mem: PageStorageType) -> Self {
ReservedInfo {}
}
}
struct FileInfo {
/// Reference count
ref_count: u64,
}
impl FileInfo {
const fn new(ref_count: u64) -> Self {
FileInfo { ref_count }
}
fn encode(&self) -> PageStorageType {
PageStorageType::new(PageType::File).encode_refcount(self.ref_count)
}
fn decode(mem: PageStorageType) -> Self {
let ref_count = mem.decode_refcount();
Self { ref_count }
}
}
enum Page {
Free(FreeInfo),
Allocated(AllocatedInfo),
SlabPage(SlabPageInfo),
CompoundPage(CompoundInfo),
FilePage(FileInfo),
Reserved(ReservedInfo),
}
impl Page {
fn to_mem(&self) -> PageStorageType {
match self {
Page::Free(fi) => fi.encode(),
Page::Allocated(ai) => ai.encode(),
Page::SlabPage(si) => si.encode(),
Page::CompoundPage(ci) => ci.encode(),
Page::FilePage(fi) => fi.encode(),
Page::Reserved(ri) => ri.encode(),
}
}
fn from_mem(mem: PageStorageType) -> Self {
let Ok(page_type) = mem.page_type() else {
panic!("Unknown page type in {:?}", mem);
};
match page_type {
PageType::Free => Self::Free(FreeInfo::decode(mem)),
PageType::Allocated => Self::Allocated(AllocatedInfo::decode(mem)),
PageType::SlabPage => Self::SlabPage(SlabPageInfo::decode(mem)),
PageType::Compound => Self::CompoundPage(CompoundInfo::decode(mem)),
PageType::File => Self::FilePage(FileInfo::decode(mem)),
PageType::Reserved => Self::Reserved(ReservedInfo::decode(mem)),
}
}
}
#[derive(Debug, Default)]
pub struct MemInfo {
total_pages: [usize; MAX_ORDER],
free_pages: [usize; MAX_ORDER],
}
#[derive(Debug, Default)]
struct MemoryRegion {
start_phys: PhysAddr,
start_virt: VirtAddr,
page_count: usize,
nr_pages: [usize; MAX_ORDER],
next_page: [usize; MAX_ORDER],
free_pages: [usize; MAX_ORDER],
}
impl MemoryRegion {
const fn new() -> Self {
Self {
start_phys: PhysAddr::null(),
start_virt: VirtAddr::null(),
page_count: 0,
nr_pages: [0; MAX_ORDER],
next_page: [0; MAX_ORDER],
free_pages: [0; MAX_ORDER],
}
}
#[allow(dead_code)]
fn phys_to_virt(&self, paddr: PhysAddr) -> Option<VirtAddr> {
let end_phys = self.start_phys + (self.page_count * PAGE_SIZE);
if paddr < self.start_phys || paddr >= end_phys {
// For the initial stage2 identity mapping, the root page table
// pages are static and outside of the heap memory region.
if VirtAddr::from(self.start_phys.bits()) == self.start_virt {
return Some(VirtAddr::from(paddr.bits()));
}
return None;
}
let offset = paddr - self.start_phys;
Some(self.start_virt + offset)
}
#[allow(dead_code)]
fn virt_to_phys(&self, vaddr: VirtAddr) -> Option<PhysAddr> {
let end_virt = self.start_virt + (self.page_count * PAGE_SIZE);
if vaddr < self.start_virt || vaddr >= end_virt {
return None;
}
let offset = vaddr - self.start_virt;
Some(self.start_phys + offset)
}
fn page_info_virt_addr(&self, pfn: usize) -> VirtAddr {
let size = size_of::<PageStorageType>();
let virt = self.start_virt;
virt + (pfn * size)
}
fn check_pfn(&self, pfn: usize) {
if pfn >= self.page_count {
panic!("Invalid Page Number {}", pfn);
}
}
fn check_virt_addr(&self, vaddr: VirtAddr) -> bool {
let start = self.start_virt;
let end = self.start_virt + (self.page_count * PAGE_SIZE);
vaddr >= start && vaddr < end
}
fn write_page_info(&self, pfn: usize, pi: Page) {
self.check_pfn(pfn);
let info: PageStorageType = pi.to_mem();
unsafe {
let ptr = self
.page_info_virt_addr(pfn)
.as_mut_ptr::<PageStorageType>();
(*ptr) = info;
}
}
fn read_page_info(&self, pfn: usize) -> Page {
self.check_pfn(pfn);
let virt = self.page_info_virt_addr(pfn).as_ptr::<u64>();
let info = unsafe { PageStorageType(*virt) };
Page::from_mem(info)
}
fn get_page_info(&self, vaddr: VirtAddr) -> Result<Page, SvsmError> {
if vaddr.is_null() || !self.check_virt_addr(vaddr) {
return Err(SvsmError::Mem);
}
let pfn = (vaddr - self.start_virt) / PAGE_SIZE;
Ok(self.read_page_info(pfn))
}
fn get_next_page(&mut self, order: usize) -> Result<usize, SvsmError> {
let pfn = self.next_page[order];
if pfn == 0 {
return Err(SvsmError::Mem);
}
let pg = self.read_page_info(pfn);
let new_next = match pg {
Page::Free(fi) => fi.next_page,
_ => panic!("Unexpected page type in MemoryRegion::get_next_page()"),
};
self.next_page[order] = new_next;
self.free_pages[order] -= 1;
Ok(pfn)
}
fn init_compound_page(&mut self, pfn: usize, order: usize, next_pfn: usize) {
let nr_pages: usize = 1 << order;
let head = Page::Free(FreeInfo {
next_page: next_pfn,
order,
});
self.write_page_info(pfn, head);
for i in 1..nr_pages {
let compound = Page::CompoundPage(CompoundInfo { order });
self.write_page_info(pfn + i, compound);
}
}
fn split_page(&mut self, pfn: usize, order: usize) -> Result<(), SvsmError> {
if !(1..MAX_ORDER).contains(&order) {
return Err(SvsmError::Mem);
}
let new_order = order - 1;
let pfn1 = pfn;
let pfn2 = pfn + (1usize << new_order);
let next_pfn = self.next_page[new_order];
self.init_compound_page(pfn1, new_order, pfn2);
self.init_compound_page(pfn2, new_order, next_pfn);
self.next_page[new_order] = pfn1;
// Do the accounting
self.nr_pages[order] -= 1;
self.nr_pages[new_order] += 2;
self.free_pages[new_order] += 2;
Ok(())
}
fn refill_page_list(&mut self, order: usize) -> Result<(), SvsmError> {
if self.next_page[order] != 0 {
return Ok(());
}
if order >= MAX_ORDER - 1 {
return Err(SvsmError::Mem);
}
self.refill_page_list(order + 1)?;
let pfn = self.get_next_page(order + 1)?;
self.split_page(pfn, order + 1)
}
fn allocate_pages(&mut self, order: usize) -> Result<VirtAddr, SvsmError> {
self.refill_page_list(order)?;
let pfn = self.get_next_page(order)?;
let pg = Page::Allocated(AllocatedInfo { order });
self.write_page_info(pfn, pg);
Ok(self.start_virt + (pfn * PAGE_SIZE))
}
fn allocate_page(&mut self) -> Result<VirtAddr, SvsmError> {
self.allocate_pages(0)
}
fn allocate_zeroed_page(&mut self) -> Result<VirtAddr, SvsmError> {
let vaddr = self.allocate_page()?;
zero_mem_region(vaddr, vaddr + PAGE_SIZE);
Ok(vaddr)
}
fn allocate_slab_page(&mut self, slab: Option<VirtAddr>) -> Result<VirtAddr, SvsmError> {
self.refill_page_list(0)?;
let slab_vaddr = slab.unwrap_or(VirtAddr::null());
let pfn = self.get_next_page(0)?;
assert_eq!(slab_vaddr.bits() & (PageStorageType::TYPE_MASK as usize), 0);
let pg = Page::SlabPage(SlabPageInfo { slab: slab_vaddr });
self.write_page_info(pfn, pg);
Ok(self.start_virt + (pfn * PAGE_SIZE))
}
fn allocate_file_page(&mut self) -> Result<VirtAddr, SvsmError> {
self.refill_page_list(0)?;
let pfn = self.get_next_page(0)?;
let pg = Page::FilePage(FileInfo::new(1));
self.write_page_info(pfn, pg);
Ok(self.start_virt + (pfn * PAGE_SIZE))
}
fn get_file_page(&mut self, vaddr: VirtAddr) -> Result<(), SvsmError> {
let page = self.get_page_info(vaddr)?;
match page {
Page::FilePage(mut fi) => {
let pfn = (vaddr - self.start_virt) / PAGE_SIZE;
assert!(fi.ref_count > 0);
fi.ref_count += 1;
self.write_page_info(pfn, Page::FilePage(fi));
Ok(())
}
_ => Err(SvsmError::Mem),
}
}
fn put_file_page(&mut self, vaddr: VirtAddr) -> Result<(), SvsmError> {
let page = self.get_page_info(vaddr)?;
match page {
Page::FilePage(mut fi) => {
let pfn = (vaddr - self.start_virt) / PAGE_SIZE;
fi.ref_count = fi
.ref_count
.checked_sub(1)
.expect("page refcount underflow");
if fi.ref_count > 0 {
self.write_page_info(pfn, Page::FilePage(fi));
} else {
self.free_page(vaddr)
}
Ok(())
}
_ => Err(SvsmError::Mem),
}
}
fn compound_neighbor(&self, pfn: usize, order: usize) -> Result<usize, SvsmError> {
if order >= MAX_ORDER - 1 {
return Err(SvsmError::Mem);
}
assert_eq!(pfn & ((1usize << order) - 1), 0);
let pfn = pfn ^ (1usize << order);
if pfn >= self.page_count {
return Err(SvsmError::Mem);
}
Ok(pfn)
}
fn merge_pages(&mut self, pfn1: usize, pfn2: usize, order: usize) -> Result<usize, SvsmError> {
if order >= MAX_ORDER - 1 {
return Err(SvsmError::Mem);
}
let nr_pages: usize = 1 << (order + 1);
let pfn = if pfn1 < pfn2 { pfn1 } else { pfn2 };
// Write new compound head
let pg = Page::Allocated(AllocatedInfo { order: order + 1 });
self.write_page_info(pfn, pg);
// Write compound pages
for i in 1..nr_pages {
let pg = Page::CompoundPage(CompoundInfo { order: order + 1 });
self.write_page_info(pfn + i, pg);
}
// Do the accounting - none of the pages is free yet, so free_pages is
// not updated here.
self.nr_pages[order] -= 2;
self.nr_pages[order + 1] += 1;
Ok(pfn)
}
fn next_free_pfn(&self, pfn: usize, order: usize) -> usize {
let page = self.read_page_info(pfn);
match page {
Page::Free(fi) => fi.next_page,
_ => {
panic!("Unexpected page type in free-list for order {}", order);
}
}
}
fn allocate_pfn(&mut self, pfn: usize, order: usize) -> Result<(), SvsmError> {
let first_pfn = self.next_page[order];
// Handle special cases first
if first_pfn == 0 {
// No pages for that order
return Err(SvsmError::Mem);
} else if first_pfn == pfn {
// Requested pfn is first in list
self.get_next_page(order).unwrap();
return Ok(());
}
// Now walk the list
let mut old_pfn = first_pfn;
loop {
let current_pfn = self.next_free_pfn(old_pfn, order);
if current_pfn == 0 {
break;
} else if current_pfn == pfn {
let next_pfn = self.next_free_pfn(current_pfn, order);
let pg = Page::Free(FreeInfo {
next_page: next_pfn,
order,
});
self.write_page_info(old_pfn, pg);
let pg = Page::Allocated(AllocatedInfo { order });
self.write_page_info(current_pfn, pg);
self.free_pages[order] -= 1;
return Ok(());
}
old_pfn = current_pfn;
}
Err(SvsmError::Mem)
}
fn free_page_raw(&mut self, pfn: usize, order: usize) {
let old_next = self.next_page[order];
let pg = Page::Free(FreeInfo {
next_page: old_next,
order,
});
self.write_page_info(pfn, pg);
self.next_page[order] = pfn;
self.free_pages[order] += 1;
}
fn try_to_merge_page(&mut self, pfn: usize, order: usize) -> Result<usize, SvsmError> {
let neighbor_pfn = self.compound_neighbor(pfn, order)?;
let neighbor_page = self.read_page_info(neighbor_pfn);
if let Page::Free(fi) = neighbor_page {
if fi.order != order {
return Err(SvsmError::Mem);
}
self.allocate_pfn(neighbor_pfn, order)?;
let new_pfn = self.merge_pages(pfn, neighbor_pfn, order)?;
Ok(new_pfn)
} else {
Err(SvsmError::Mem)
}
}
fn free_page_order(&mut self, pfn: usize, order: usize) {
match self.try_to_merge_page(pfn, order) {
Err(_) => {
self.free_page_raw(pfn, order);
}
Ok(new_pfn) => {
self.free_page_order(new_pfn, order + 1);
}
}
}
fn free_page(&mut self, vaddr: VirtAddr) {
let Ok(res) = self.get_page_info(vaddr) else {
return;
};
let pfn = (vaddr - self.start_virt) / PAGE_SIZE;
match res {
Page::Allocated(ai) => {
self.free_page_order(pfn, ai.order);
}
Page::SlabPage(_si) => {
self.free_page_order(pfn, 0);
}
Page::CompoundPage(ci) => {
let mask = (1usize << ci.order) - 1;
let start_pfn = pfn & !mask;
self.free_page_order(start_pfn, ci.order);
}
Page::FilePage(_) => {
self.free_page_order(pfn, 0);
}
_ => {
panic!("Unexpected page type in MemoryRegion::free_page()");
}
}
}
fn memory_info(&self) -> MemInfo {
MemInfo {
total_pages: self.nr_pages,
free_pages: self.free_pages,
}
}
fn init_memory(&mut self) {
let size = size_of::<PageStorageType>();
let meta_pages = align_up(self.page_count * size, PAGE_SIZE) / PAGE_SIZE;
/* Mark page storage as reserved */
for i in 0..meta_pages {
let pg: Page = Page::Reserved(ReservedInfo {});
self.write_page_info(i, pg);
}
self.nr_pages[0] = self.page_count - meta_pages;
/* Mark all pages as allocated */
for i in meta_pages..self.page_count {
let pg = Page::Allocated(AllocatedInfo { order: 0 });
self.write_page_info(i, pg);
}
/* Now free all pages */
for i in meta_pages..self.page_count {
self.free_page_order(i, 0);
}
}
}
#[derive(Debug)]
pub struct PageRef {
virt_addr: VirtAddr,
phys_addr: PhysAddr,
}
impl PageRef {
pub const fn new(virt_addr: VirtAddr, phys_addr: PhysAddr) -> Self {
PageRef {
virt_addr,
phys_addr,
}
}
pub fn virt_addr(&self) -> VirtAddr {
self.virt_addr
}
}
impl AsRef<[u8; PAGE_SIZE]> for PageRef {
fn as_ref(&self) -> &[u8; PAGE_SIZE] {
let ptr = self.virt_addr.as_ptr::<[u8; PAGE_SIZE]>();
unsafe { ptr.as_ref().unwrap() }
}
}
impl AsMut<[u8; PAGE_SIZE]> for PageRef {
fn as_mut(&mut self) -> &mut [u8; PAGE_SIZE] {
let ptr = self.virt_addr.as_mut_ptr::<[u8; PAGE_SIZE]>();
unsafe { ptr.as_mut().unwrap() }
}
}
impl Clone for PageRef {
fn clone(&self) -> Self {
get_file_page(self.virt_addr).expect("Failed to get page reference");
PageRef {
virt_addr: self.virt_addr,
phys_addr: self.phys_addr,
}
}
}
impl Drop for PageRef {
fn drop(&mut self) {
put_file_page(self.virt_addr).expect("Failed to drop page reference");
}
}
pub fn print_memory_info(info: &MemInfo) {
let mut pages_4k = 0;
let mut free_pages_4k = 0;
for i in 0..MAX_ORDER {
let nr_4k_pages: usize = 1 << i;
log::info!(
"Order-{:#02}: total pages: {:#5} free pages: {:#5}",
i,
info.total_pages[i],
info.free_pages[i]
);
pages_4k += info.total_pages[i] * nr_4k_pages;
free_pages_4k += info.free_pages[i] * nr_4k_pages;
}
log::info!(
"Total memory: {}KiB free memory: {}KiB",
(pages_4k * PAGE_SIZE) / 1024,
(free_pages_4k * PAGE_SIZE) / 1024
);
}
static ROOT_MEM: SpinLock<MemoryRegion> = SpinLock::new(MemoryRegion::new());
pub fn allocate_page() -> Result<VirtAddr, SvsmError> {
ROOT_MEM.lock().allocate_page()
}
pub fn allocate_pages(order: usize) -> Result<VirtAddr, SvsmError> {
ROOT_MEM.lock().allocate_pages(order)
}
pub fn allocate_slab_page(slab: Option<VirtAddr>) -> Result<VirtAddr, SvsmError> {
ROOT_MEM.lock().allocate_slab_page(slab)
}
pub fn allocate_zeroed_page() -> Result<VirtAddr, SvsmError> {
ROOT_MEM.lock().allocate_zeroed_page()
}
pub fn allocate_file_page() -> Result<VirtAddr, SvsmError> {
let vaddr = ROOT_MEM.lock().allocate_file_page()?;
zero_mem_region(vaddr, vaddr + PAGE_SIZE);
Ok(vaddr)
}
pub fn allocate_file_page_ref() -> Result<PageRef, SvsmError> {
let v = allocate_file_page()?;
let p = virt_to_phys(v);
Ok(PageRef::new(v, p))
}
pub fn get_file_page(vaddr: VirtAddr) -> Result<(), SvsmError> {
ROOT_MEM.lock().get_file_page(vaddr)
}
pub fn put_file_page(vaddr: VirtAddr) -> Result<(), SvsmError> {
ROOT_MEM.lock().put_file_page(vaddr)
}
pub fn free_page(vaddr: VirtAddr) {
ROOT_MEM.lock().free_page(vaddr)
}
pub fn memory_info() -> MemInfo {
ROOT_MEM.lock().memory_info()
}
#[derive(Debug, Default)]
struct SlabPage {
vaddr: VirtAddr,
capacity: u16,
free: u16,
item_size: u16,
used_bitmap: [u64; 2],
next_page: VirtAddr,
}
impl SlabPage {
const fn new() -> Self {
SlabPage {
vaddr: VirtAddr::null(),
capacity: 0,
free: 0,
item_size: 0,
used_bitmap: [0; 2],
next_page: VirtAddr::null(),
}
}
fn init(&mut self, slab_vaddr: Option<VirtAddr>, mut item_size: u16) -> Result<(), SvsmError> {
if self.item_size != 0 {
return Ok(());
}
assert!(item_size <= (PAGE_SIZE / 2) as u16);
assert!(self.vaddr.is_null());
if item_size < 32 {
item_size = 32;
}
let vaddr = allocate_slab_page(slab_vaddr)?;
self.vaddr = vaddr;
self.item_size = item_size;
self.capacity = (PAGE_SIZE as u16) / item_size;
self.free = self.capacity;
Ok(())
}
fn destroy(&mut self) {
if self.vaddr.is_null() {
return;
}
free_page(self.vaddr);
}
fn get_capacity(&self) -> u16 {
self.capacity
}
fn get_free(&self) -> u16 {
self.free
}
fn get_next_page(&self) -> VirtAddr {
self.next_page
}
fn set_next_page(&mut self, next_page: VirtAddr) {
self.next_page = next_page;
}
fn allocate(&mut self) -> Result<VirtAddr, SvsmError> {
if self.free == 0 {
return Err(SvsmError::Mem);
}
for i in 0..self.capacity {
let idx = (i / 64) as usize;
let mask = 1u64 << (i % 64);
if self.used_bitmap[idx] & mask == 0 {
self.used_bitmap[idx] |= mask;
self.free -= 1;
return Ok(self.vaddr + ((self.item_size * i) as usize));
}
}
Err(SvsmError::Mem)
}
fn free(&mut self, vaddr: VirtAddr) -> Result<(), SvsmError> {
if vaddr < self.vaddr || vaddr >= self.vaddr + PAGE_SIZE {
return Err(SvsmError::Mem);
}
assert!(self.item_size > 0);
let item_size = self.item_size as usize;
let offset = vaddr - self.vaddr;
let i = offset / item_size;
let idx = i / 64;
let mask = 1u64 << (i % 64);
self.used_bitmap[idx] &= !mask;
self.free += 1;
Ok(())
}
}
#[derive(Debug, Default)]
#[repr(align(16))]
struct SlabCommon {
item_size: u16,
capacity: u32,
free: u32,
pages: u32,
full_pages: u32,
free_pages: u32,
page: SlabPage,
}
impl SlabCommon {
const fn new(item_size: u16) -> Self {
SlabCommon {
item_size,
capacity: 0,
free: 0,
pages: 0,
full_pages: 0,
free_pages: 0,
page: SlabPage::new(),
}
}
fn init(&mut self, slab_vaddr: Option<VirtAddr>) -> Result<(), SvsmError> {
self.page.init(slab_vaddr, self.item_size)?;
self.capacity = self.page.get_capacity() as u32;
self.free = self.capacity;
self.pages = 1;
self.full_pages = 0;
self.free_pages = 1;
Ok(())
}
fn add_slab_page(&mut self, new_page: &mut SlabPage) {
let old_next_page = self.page.get_next_page();
new_page.set_next_page(old_next_page);
self.page
.set_next_page(VirtAddr::from(new_page as *mut SlabPage));
let capacity = new_page.get_capacity() as u32;
self.pages += 1;
self.free_pages += 1;
self.capacity += capacity;
self.free += capacity;
}
fn remove_slab_page(&mut self, prev_page: &mut SlabPage, old_page: &SlabPage) {
let capacity = old_page.get_capacity() as u32;
self.pages -= 1;
self.free_pages -= 1;
self.capacity -= capacity;
self.free -= capacity;
prev_page.set_next_page(old_page.get_next_page());
}
fn allocate_slot(&mut self) -> VirtAddr {
// Caller must make sure there's at least one free slot.
assert_ne!(self.free, 0);
let mut page = &mut self.page;
loop {
let free = page.get_free();
if let Ok(vaddr) = page.allocate() {
let capacity = page.get_capacity();
self.free -= 1;
if free == capacity {
self.free_pages -= 1;
} else if free == 1 {
self.full_pages += 1;
}
return vaddr;
}
let next_page = (*page).get_next_page();
assert!(!next_page.is_null()); // Cannot happen with free slots on entry.