-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathmain.rs
More file actions
3627 lines (3303 loc) · 130 KB
/
main.rs
File metadata and controls
3627 lines (3303 loc) · 130 KB
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
//
// Copyright 2024, UNSW
//
// SPDX-License-Identifier: BSD-2-Clause
//
// we want our asserts, even if the compiler figures out they hold true already during compile-time
#![allow(clippy::assertions_on_constants)]
use elf::ElfFile;
use loader::Loader;
use microkit_tool::{
elf, loader, sdf, sel4, util, DisjointMemoryRegion, MemoryRegion, ObjectAllocator, Region,
UntypedObject, MAX_PDS, PD_MAX_NAME_LENGTH,
};
use sdf::{
parse, ProtectionDomain, SysMap, SysMapPerms, SysMemoryRegion, SystemDescription,
VirtualMachine,
};
use sel4::{
default_vm_attr, Aarch64Regs, Arch, ArmVmAttributes, BootInfo, Config, Invocation,
InvocationArgs, Object, ObjectType, PageSize, Rights, Riscv64Regs, RiscvVirtualMemory,
RiscvVmAttributes,
};
use std::cmp::{max, min};
use std::collections::{HashMap, HashSet};
use std::fs;
use std::io::{BufWriter, Write};
use std::iter::zip;
use std::mem::size_of;
use std::path::{Path, PathBuf};
use util::{
bytes_to_struct, comma_sep_u64, comma_sep_usize, json_str, json_str_as_bool, json_str_as_u64,
monitor_serialise_u64_vec, struct_to_bytes,
};
// Corresponds to the IPC buffer symbol in libmicrokit and the monitor
const SYMBOL_IPC_BUFFER: &str = "__sel4_ipc_buffer_obj";
const FAULT_BADGE: u64 = 1 << 62;
const PPC_BADGE: u64 = 1 << 63;
const INPUT_CAP_IDX: u64 = 1;
#[allow(dead_code)]
const FAULT_EP_CAP_IDX: u64 = 2;
const VSPACE_CAP_IDX: u64 = 3;
const REPLY_CAP_IDX: u64 = 4;
const MONITOR_EP_CAP_IDX: u64 = 5;
const TCB_CAP_IDX: u64 = 6;
const SMC_CAP_IDX: u64 = 7;
const BASE_OUTPUT_NOTIFICATION_CAP: u64 = 10;
const BASE_OUTPUT_ENDPOINT_CAP: u64 = BASE_OUTPUT_NOTIFICATION_CAP + 64;
const BASE_IRQ_CAP: u64 = BASE_OUTPUT_ENDPOINT_CAP + 64;
const BASE_PD_TCB_CAP: u64 = BASE_IRQ_CAP + 64;
const BASE_VM_TCB_CAP: u64 = BASE_PD_TCB_CAP + 64;
const BASE_VCPU_CAP: u64 = BASE_VM_TCB_CAP + 64;
const MAX_SYSTEM_INVOCATION_SIZE: u64 = util::mb(128);
const PD_CAP_SIZE: u64 = 512;
const PD_CAP_BITS: u64 = PD_CAP_SIZE.ilog2() as u64;
const PD_SCHEDCONTEXT_SIZE: u64 = 1 << 8;
const SLOT_BITS: u64 = 5;
const SLOT_SIZE: u64 = 1 << SLOT_BITS;
const INIT_NULL_CAP_ADDRESS: u64 = 0;
const INIT_TCB_CAP_ADDRESS: u64 = 1;
const INIT_CNODE_CAP_ADDRESS: u64 = 2;
const INIT_VSPACE_CAP_ADDRESS: u64 = 3;
const IRQ_CONTROL_CAP_ADDRESS: u64 = 4; // Singleton
const INIT_ASID_POOL_CAP_ADDRESS: u64 = 6;
const SMC_CAP_ADDRESS: u64 = 15;
// const ASID_CONTROL_CAP_ADDRESS: u64 = 5; // Singleton
// const IO_PORT_CONTROL_CAP_ADDRESS: u64 = 7; // Null on this platform
// const IO_SPACE_CAP_ADDRESS: u64 = 8; // Null on this platform
// const BOOT_INFO_FRAME_CAP_ADDRESS: u64 = 9;
// const INIT_THREAD_IPC_BUFFER_CAP_ADDRESS: u64 = 10;
// const DOMAIN_CAP_ADDRESS: u64 = 11;
// const SMMU_SID_CONTROL_CAP_ADDRESS: u64 = 12;
// const SMMU_CB_CONTROL_CAP_ADDRESS: u64 = 13;
// const INIT_THREAD_SC_CAP_ADDRESS: u64 = 14;
/// Corresponds to 'struct untyped_info' in the monitor
/// It should be noted that this is called a 'header' since
/// it omits the 'regions' field.
/// This struct assumes a 64-bit target
#[repr(C)]
struct MonitorUntypedInfoHeader64 {
cap_start: u64,
cap_end: u64,
}
/// Corresponds to 'struct region' in the monitor
/// This struct assumes a 64-bit target
#[repr(C)]
struct MonitorRegion64 {
paddr: u64,
size_bits: u64,
is_device: u64,
}
struct MonitorConfig {
untyped_info_symbol_name: &'static str,
bootstrap_invocation_count_symbol_name: &'static str,
bootstrap_invocation_data_symbol_name: &'static str,
system_invocation_count_symbol_name: &'static str,
}
impl MonitorConfig {
pub fn max_untyped_objects(&self, symbol_size: u64) -> u64 {
(symbol_size - size_of::<MonitorUntypedInfoHeader64>() as u64)
/ size_of::<MonitorRegion64>() as u64
}
}
#[derive(Debug)]
struct FixedUntypedAlloc {
ut: UntypedObject,
watermark: u64,
}
impl FixedUntypedAlloc {
pub fn new(ut: UntypedObject) -> FixedUntypedAlloc {
FixedUntypedAlloc {
ut,
watermark: ut.base(),
}
}
pub fn contains(&self, addr: u64) -> bool {
self.ut.base() <= addr && addr < self.ut.end()
}
}
struct InitSystem<'a> {
config: &'a Config,
cnode_cap: u64,
cnode_mask: u64,
kao: &'a mut ObjectAllocator,
invocations: &'a mut Vec<Invocation>,
cap_slot: u64,
last_fixed_address: u64,
normal_untyped: Vec<FixedUntypedAlloc>,
device_untyped: Vec<FixedUntypedAlloc>,
cap_address_names: &'a mut HashMap<u64, String>,
objects: Vec<Object>,
}
impl<'a> InitSystem<'a> {
#[allow(clippy::too_many_arguments)] // just this one time, pinky-promise...
pub fn new(
config: &'a Config,
cnode_cap: u64,
cnode_mask: u64,
first_available_cap_slot: u64,
kernel_object_allocator: &'a mut ObjectAllocator,
kernel_boot_info: &'a BootInfo,
invocations: &'a mut Vec<Invocation>,
cap_address_names: &'a mut HashMap<u64, String>,
) -> InitSystem<'a> {
let mut device_untyped: Vec<FixedUntypedAlloc> = kernel_boot_info
.untyped_objects
.iter()
.filter_map(|ut| {
if ut.is_device {
Some(FixedUntypedAlloc::new(*ut))
} else {
None
}
})
.collect();
device_untyped.sort_by(|a, b| a.ut.base().cmp(&b.ut.base()));
let mut normal_untyped: Vec<FixedUntypedAlloc> = kernel_boot_info
.untyped_objects
.iter()
.filter_map(|ut| {
if !ut.is_device {
Some(FixedUntypedAlloc::new(*ut))
} else {
None
}
})
.collect();
normal_untyped.sort_by(|a, b| a.ut.base().cmp(&b.ut.base()));
InitSystem {
config,
cnode_cap,
cnode_mask,
kao: kernel_object_allocator,
invocations,
cap_slot: first_available_cap_slot,
last_fixed_address: 0,
normal_untyped,
device_untyped,
cap_address_names,
objects: Vec::new(),
}
}
pub fn reserve(&mut self, allocations: Vec<(&UntypedObject, u64)>) {
for (alloc_ut, alloc_phys_addr) in allocations {
let mut found = false;
for fut in &mut self.device_untyped {
if *alloc_ut == fut.ut {
if fut.ut.base() <= alloc_phys_addr && alloc_phys_addr <= fut.ut.end() {
fut.watermark = alloc_phys_addr;
found = true;
break;
} else {
panic!(
"Allocation {:?} ({:x}) not in untyped region {:?}",
alloc_ut, alloc_phys_addr, fut.ut.region
);
}
}
}
if !found {
panic!(
"Allocation {:?} ({:x}) not in any device untyped",
alloc_ut, alloc_phys_addr
);
}
}
}
/// Note: Fixed objects must be allocated in order!
pub fn allocate_fixed_object(
&mut self,
phys_address: u64,
object_type: ObjectType,
name: String,
) -> Object {
assert!(phys_address >= self.last_fixed_address);
assert!(object_type.fixed_size(self.config).is_some());
let alloc_size = object_type.fixed_size(self.config).unwrap();
// Find an untyped that contains the given address, it may be in device
// memory
let device_fut: Option<&mut FixedUntypedAlloc> = self
.device_untyped
.iter_mut()
.find(|fut| fut.contains(phys_address));
let normal_fut: Option<&mut FixedUntypedAlloc> = self
.normal_untyped
.iter_mut()
.find(|fut| fut.contains(phys_address));
// We should never have found the physical address in both device and normal untyped
assert!(!(device_fut.is_some() && normal_fut.is_some()));
let fut = if let Some(fut) = device_fut {
fut
} else if let Some(fut) = normal_fut {
fut
} else {
panic!(
"Error: physical address {:x} not in any device untyped",
phys_address
)
};
let space_left = fut.ut.region.end - fut.watermark;
if space_left < alloc_size {
for ut in &self.device_untyped {
let space_left = ut.ut.region.end - ut.watermark;
println!(
"ut [0x{:x}..0x{:x}], space left: 0x{:x}",
ut.ut.region.base, ut.ut.region.end, space_left
);
}
panic!(
"Error: allocation for physical address {:x} is too large ({:x}) for untyped",
phys_address, alloc_size
);
}
if phys_address < fut.watermark {
panic!(
"Error: physical address {:x} is below watermark",
phys_address
);
}
if fut.watermark != phys_address {
// If the watermark isn't at the right spot, then we need to
// create padding objects until it is.
let mut padding_required = phys_address - fut.watermark;
// We are restricted in how much we can pad:
// 1: Untyped objects must be power-of-two sized.
// 2: Untyped objects must be aligned to their size.
let mut padding_sizes = Vec::new();
// We have two potential approaches for how we pad.
// 1: Use largest objects possible respecting alignment
// and size restrictions.
// 2: Use a fixed size object multiple times. This will
// create more objects, but as same sized objects can be
// create in a batch, required fewer invocations.
// For now we choose #1
let mut wm = fut.watermark;
while padding_required > 0 {
let wm_lsb = util::lsb(wm);
let sz_msb = util::msb(padding_required);
let pad_obejct_size = 1 << min(wm_lsb, sz_msb);
padding_sizes.push(pad_obejct_size);
wm += pad_obejct_size;
padding_required -= pad_obejct_size;
}
for sz in padding_sizes {
self.invocations.push(Invocation::new(
self.config,
InvocationArgs::UntypedRetype {
untyped: fut.ut.cap,
object_type: ObjectType::Untyped,
size_bits: sz.ilog2() as u64,
root: self.cnode_cap,
node_index: 1,
node_depth: 1,
node_offset: self.cap_slot,
num_objects: 1,
},
));
self.cap_slot += 1;
}
}
let object_cap = self.cap_slot;
self.cap_slot += 1;
self.invocations.push(Invocation::new(
self.config,
InvocationArgs::UntypedRetype {
untyped: fut.ut.cap,
object_type,
size_bits: 0,
root: self.cnode_cap,
node_index: 1,
node_depth: 1,
node_offset: object_cap,
num_objects: 1,
},
));
fut.watermark = phys_address + alloc_size;
self.last_fixed_address = phys_address + alloc_size;
let cap_addr = self.cnode_mask | object_cap;
let kernel_object = Object {
object_type,
cap_addr,
phys_addr: phys_address,
};
self.objects.push(kernel_object);
self.cap_address_names.insert(cap_addr, name);
kernel_object
}
pub fn allocate_objects(
&mut self,
object_type: ObjectType,
names: Vec<String>,
size: Option<u64>,
) -> Vec<Object> {
// Nothing to do if we get a zero count.
if names.is_empty() {
return Vec::new();
}
let count = names.len() as u64;
let alloc_size;
let api_size: u64;
if let Some(object_size) = object_type.fixed_size(self.config) {
// An object with a fixed size should not be allocated with a given size
assert!(size.is_none());
alloc_size = object_size;
api_size = 0;
} else if object_type == ObjectType::CNode || object_type == ObjectType::SchedContext {
let sz = size.unwrap();
assert!(util::is_power_of_two(sz));
api_size = sz.ilog2() as u64;
alloc_size = sz * SLOT_SIZE;
} else {
panic!("Internal error: invalid object type: {:?}", object_type);
}
let allocation = self.kao.alloc_n(alloc_size, count);
let base_cap_slot = self.cap_slot;
self.cap_slot += count;
let mut to_alloc = count;
let mut alloc_cap_slot = base_cap_slot;
while to_alloc > 0 {
let call_count = min(to_alloc, self.config.fan_out_limit);
self.invocations.push(Invocation::new(
self.config,
InvocationArgs::UntypedRetype {
untyped: allocation.untyped_cap_address,
object_type,
size_bits: api_size,
root: self.cnode_cap,
node_index: 1,
node_depth: 1,
node_offset: alloc_cap_slot,
num_objects: call_count,
},
));
to_alloc -= call_count;
alloc_cap_slot += call_count;
}
let mut kernel_objects = Vec::new();
let mut phys_addr = allocation.phys_addr;
for (idx, name) in names.into_iter().enumerate() {
let cap_slot = base_cap_slot + idx as u64;
let cap_addr = self.cnode_mask | cap_slot;
let kernel_object = Object {
object_type,
cap_addr,
phys_addr,
};
kernel_objects.push(kernel_object);
self.cap_address_names.insert(cap_addr, name);
phys_addr += alloc_size;
self.objects.push(kernel_object);
}
kernel_objects
}
}
struct BuiltSystem {
number_of_system_caps: u64,
invocation_data: Vec<u8>,
invocation_data_size: u64,
bootstrap_invocations: Vec<Invocation>,
system_invocations: Vec<Invocation>,
kernel_boot_info: BootInfo,
reserved_region: MemoryRegion,
fault_ep_cap_address: u64,
reply_cap_address: u64,
cap_lookup: HashMap<u64, String>,
tcb_caps: Vec<u64>,
sched_caps: Vec<u64>,
ntfn_caps: Vec<u64>,
pd_elf_regions: Vec<Vec<Region>>,
pd_setvar_values: Vec<Vec<u64>>,
pd_stack_addrs: Vec<u64>,
kernel_objects: Vec<Object>,
initial_task_virt_region: MemoryRegion,
initial_task_phys_region: MemoryRegion,
}
pub fn pd_write_symbols(
pds: &[ProtectionDomain],
pd_elf_files: &mut [ElfFile],
pd_setvar_values: &[Vec<u64>],
) -> Result<(), String> {
for (i, pd) in pds.iter().enumerate() {
let elf = &mut pd_elf_files[i];
let name = pd.name.as_bytes();
let name_length = min(name.len(), PD_MAX_NAME_LENGTH);
elf.write_symbol("microkit_name", &name[..name_length])?;
elf.write_symbol("microkit_passive", &[pd.passive as u8])?;
for (setvar_idx, setvar) in pd.setvars.iter().enumerate() {
let value = pd_setvar_values[i][setvar_idx];
let result = elf.write_symbol(&setvar.symbol, &value.to_le_bytes());
if result.is_err() {
return Err(format!(
"No symbol named '{}' in ELF '{}' for PD '{}'",
setvar.symbol,
pd.program_image.display(),
pd.name
));
}
}
}
Ok(())
}
/// Determine the physical memory regions for an ELF file with a given
/// alignment.
///
/// The returned region shall be extended (if necessary) so that the start
/// and end are congruent with the specified alignment (usually a page size).
fn phys_mem_regions_from_elf(elf: &ElfFile, alignment: u64) -> Vec<MemoryRegion> {
assert!(alignment > 0);
elf.segments
.iter()
.filter(|s| s.loadable)
.map(|s| {
MemoryRegion::new(
util::round_down(s.phys_addr, alignment),
util::round_up(s.phys_addr + s.data.len() as u64, alignment),
)
})
.collect()
}
/// Determine a single physical memory region for an ELF.
///
/// Works as per phys_mem_regions_from_elf, but checks the ELF has a single
/// segment, and returns the region covering the first segment.
fn phys_mem_region_from_elf(elf: &ElfFile, alignment: u64) -> MemoryRegion {
assert!(alignment > 0);
assert!(elf.segments.iter().filter(|s| s.loadable).count() == 1);
phys_mem_regions_from_elf(elf, alignment)[0]
}
/// Determine the virtual memory regions for an ELF file with a given
/// alignment.
/// The returned region shall be extended (if necessary) so that the start
/// and end are congruent with the specified alignment (usually a page size).
fn virt_mem_regions_from_elf(elf: &ElfFile, alignment: u64) -> Vec<MemoryRegion> {
assert!(alignment > 0);
elf.segments
.iter()
.filter(|s| s.loadable)
.map(|s| {
MemoryRegion::new(
util::round_down(s.virt_addr, alignment),
util::round_up(s.virt_addr + s.data.len() as u64, alignment),
)
})
.collect()
}
/// Determine a single virtual memory region for an ELF.
///
/// Works as per virt_mem_regions_from_elf, but checks the ELF has a single
/// segment, and returns the region covering the first segment.
fn virt_mem_region_from_elf(elf: &ElfFile, alignment: u64) -> MemoryRegion {
assert!(alignment > 0);
assert!(elf.segments.iter().filter(|s| s.loadable).count() == 1);
virt_mem_regions_from_elf(elf, alignment)[0]
}
fn get_full_path(path: &Path, search_paths: &Vec<PathBuf>) -> Option<PathBuf> {
for search_path in search_paths {
let full_path = search_path.join(path);
if full_path.exists() {
return Some(full_path.to_path_buf());
}
}
None
}
struct KernelPartialBootInfo {
device_memory: DisjointMemoryRegion,
normal_memory: DisjointMemoryRegion,
boot_region: MemoryRegion,
}
// Corresponds to kernel_frame_t in the kernel
#[repr(C)]
struct KernelFrameRiscv64 {
pub paddr: u64,
pub pptr: u64,
pub user_accessible: i32,
}
#[repr(C)]
struct KernelFrameAarch64 {
pub paddr: u64,
pub pptr: u64,
pub execute_never: i32,
pub user_accessible: i32,
}
fn kernel_device_addrs(config: &Config, kernel_elf: &ElfFile) -> Vec<u64> {
assert!(config.word_size == 64, "Unsupported word-size");
let mut kernel_devices = Vec::new();
let (vaddr, size) = kernel_elf
.find_symbol("kernel_device_frames")
.expect("Could not find 'kernel_device_frames' symbol");
let kernel_frame_bytes = kernel_elf.get_data(vaddr, size).unwrap();
let kernel_frame_size = match config.arch {
Arch::Aarch64 => size_of::<KernelFrameAarch64>(),
Arch::Riscv64 => size_of::<KernelFrameRiscv64>(),
};
let mut offset: usize = 0;
while offset < size as usize {
let (user_accessible, paddr) = unsafe {
match config.arch {
Arch::Aarch64 => {
let frame = bytes_to_struct::<KernelFrameAarch64>(
&kernel_frame_bytes[offset..offset + kernel_frame_size],
);
(frame.user_accessible, frame.paddr)
}
Arch::Riscv64 => {
let frame = bytes_to_struct::<KernelFrameRiscv64>(
&kernel_frame_bytes[offset..offset + kernel_frame_size],
);
(frame.user_accessible, frame.paddr)
}
}
};
if user_accessible == 0 {
kernel_devices.push(paddr);
}
offset += kernel_frame_size;
}
kernel_devices
}
// Corresponds to p_region_t in the kernel
#[repr(C)]
struct KernelRegion64 {
start: u64,
end: u64,
}
fn kernel_phys_mem(kernel_config: &Config, kernel_elf: &ElfFile) -> Vec<(u64, u64)> {
assert!(kernel_config.word_size == 64, "Unsupported word-size");
let mut phys_mem = Vec::new();
let (vaddr, size) = kernel_elf
.find_symbol("avail_p_regs")
.expect("Could not find 'avail_p_regs' symbol");
let p_region_bytes = kernel_elf.get_data(vaddr, size).unwrap();
let p_region_size = size_of::<KernelRegion64>();
let mut offset: usize = 0;
while offset < size as usize {
let p_region = unsafe {
bytes_to_struct::<KernelRegion64>(&p_region_bytes[offset..offset + p_region_size])
};
phys_mem.push((p_region.start, p_region.end));
offset += p_region_size;
}
phys_mem
}
fn kernel_self_mem(kernel_elf: &ElfFile) -> MemoryRegion {
let segments = kernel_elf.loadable_segments();
let base = segments[0].phys_addr;
let (ki_end_v, _) = kernel_elf
.find_symbol("ki_end")
.expect("Could not find 'ki_end' symbol");
let ki_end_p = ki_end_v - segments[0].virt_addr + base;
MemoryRegion::new(base, ki_end_p)
}
fn kernel_boot_mem(kernel_elf: &ElfFile) -> MemoryRegion {
let segments = kernel_elf.loadable_segments();
let base = segments[0].phys_addr;
let (ki_boot_end_v, _) = kernel_elf
.find_symbol("ki_boot_end")
.expect("Could not find 'ki_boot_end' symbol");
let ki_boot_end_p = ki_boot_end_v - segments[0].virt_addr + base;
MemoryRegion::new(base, ki_boot_end_p)
}
///
/// Emulate what happens during a kernel boot, up to the point
/// where the reserved region is allocated.
///
/// This factors the common parts of 'emulate_kernel_boot' and
/// 'emulate_kernel_boot_partial' to avoid code duplication.
///
fn kernel_partial_boot(kernel_config: &Config, kernel_elf: &ElfFile) -> KernelPartialBootInfo {
// Determine the untyped caps of the system
// This lets allocations happen correctly.
let mut device_memory = DisjointMemoryRegion::default();
let mut normal_memory = DisjointMemoryRegion::default();
// Start by allocating the entire physical address space
// as device memory.
device_memory.insert_region(0, kernel_config.paddr_user_device_top);
// Next, remove all the kernel devices.
// NOTE: There is an assumption each kernel device is one frame
// in size only. It's possible this assumption could break in the
// future.
for paddr in kernel_device_addrs(kernel_config, kernel_elf) {
device_memory.remove_region(paddr, paddr + kernel_config.kernel_frame_size);
}
// Remove all the actual physical memory from the device regions
// but add it all to the actual normal memory regions
for (start, end) in kernel_phys_mem(kernel_config, kernel_elf) {
device_memory.remove_region(start, end);
normal_memory.insert_region(start, end);
}
// Remove the kernel image itself
let self_mem = kernel_self_mem(kernel_elf);
normal_memory.remove_region(self_mem.base, self_mem.end);
// but get the boot region, we'll add that back later
// FIXME: Why calcaultae it now if we add it back later?
let boot_region = kernel_boot_mem(kernel_elf);
KernelPartialBootInfo {
device_memory,
normal_memory,
boot_region,
}
}
fn emulate_kernel_boot_partial(
kernel_config: &Config,
kernel_elf: &ElfFile,
) -> (DisjointMemoryRegion, MemoryRegion) {
let partial_info = kernel_partial_boot(kernel_config, kernel_elf);
(partial_info.normal_memory, partial_info.boot_region)
}
fn get_n_paging(region: MemoryRegion, bits: u64) -> u64 {
let start = util::round_down(region.base, 1 << bits);
let end = util::round_up(region.end, 1 << bits);
(end - start) / (1 << bits)
}
fn get_arch_n_paging(config: &Config, region: MemoryRegion) -> u64 {
match config.arch {
Arch::Aarch64 => {
const PT_INDEX_OFFSET: u64 = 12;
const PD_INDEX_OFFSET: u64 = PT_INDEX_OFFSET + 9;
const PUD_INDEX_OFFSET: u64 = PD_INDEX_OFFSET + 9;
get_n_paging(region, PUD_INDEX_OFFSET) + get_n_paging(region, PD_INDEX_OFFSET)
}
Arch::Riscv64 => match config.riscv_pt_levels.unwrap() {
RiscvVirtualMemory::Sv39 => {
const PT_INDEX_OFFSET: u64 = 12;
const LVL1_INDEX_OFFSET: u64 = PT_INDEX_OFFSET + 9;
const LVL2_INDEX_OFFSET: u64 = LVL1_INDEX_OFFSET + 9;
get_n_paging(region, LVL2_INDEX_OFFSET) + get_n_paging(region, LVL1_INDEX_OFFSET)
}
},
}
}
fn rootserver_max_size_bits(config: &Config) -> u64 {
let slot_bits = 5; // seL4_SlotBits
let root_cnode_bits = config.init_cnode_bits; // CONFIG_ROOT_CNODE_SIZE_BITS
let vspace_bits = ObjectType::VSpace.fixed_size_bits(config).unwrap();
let cnode_size_bits = root_cnode_bits + slot_bits;
max(cnode_size_bits, vspace_bits)
}
fn calculate_rootserver_size(config: &Config, initial_task_region: MemoryRegion) -> u64 {
// FIXME: These constants should ideally come from the config / kernel
// binary not be hard coded here.
// But they are constant so it isn't too bad.
let slot_bits = 5; // seL4_SlotBits
let root_cnode_bits = config.init_cnode_bits; // CONFIG_ROOT_CNODE_SIZE_BITS
let tcb_bits = ObjectType::Tcb.fixed_size_bits(config).unwrap(); // seL4_TCBBits
let page_bits = ObjectType::SmallPage.fixed_size_bits(config).unwrap(); // seL4_PageBits
let asid_pool_bits = 12; // seL4_ASIDPoolBits
let vspace_bits = ObjectType::VSpace.fixed_size_bits(config).unwrap(); // seL4_VSpaceBits
let page_table_bits = ObjectType::PageTable.fixed_size_bits(config).unwrap(); // seL4_PageTableBits
let min_sched_context_bits = 7; // seL4_MinSchedContextBits
let mut size = 0;
size += 1 << (root_cnode_bits + slot_bits);
size += 1 << (tcb_bits);
size += 2 * (1 << page_bits);
size += 1 << asid_pool_bits;
size += 1 << vspace_bits;
size += get_arch_n_paging(config, initial_task_region) * (1 << page_table_bits);
size += 1 << min_sched_context_bits;
size
}
/// Emulate what happens during a kernel boot, generating a
/// representation of the BootInfo struct.
fn emulate_kernel_boot(
config: &Config,
kernel_elf: &ElfFile,
initial_task_phys_region: MemoryRegion,
initial_task_virt_region: MemoryRegion,
reserved_region: MemoryRegion,
) -> BootInfo {
assert!(initial_task_phys_region.size() == initial_task_virt_region.size());
let partial_info = kernel_partial_boot(config, kernel_elf);
let mut normal_memory = partial_info.normal_memory;
let device_memory = partial_info.device_memory;
let boot_region = partial_info.boot_region;
normal_memory.remove_region(initial_task_phys_region.base, initial_task_phys_region.end);
normal_memory.remove_region(reserved_region.base, reserved_region.end);
// Now, the tricky part! determine which memory is used for the initial task objects
let initial_objects_size = calculate_rootserver_size(config, initial_task_virt_region);
let initial_objects_align = rootserver_max_size_bits(config);
// Find an appropriate region of normal memory to allocate the objects
// from; this follows the same algorithm used within the kernel boot code
// (or at least we hope it does!)
// TOOD: this loop could be done better in a functional way?
let mut region_to_remove: Option<u64> = None;
for region in normal_memory.regions.iter().rev() {
let start = util::round_down(
region.end - initial_objects_size,
1 << initial_objects_align,
);
if start >= region.base {
region_to_remove = Some(start);
break;
}
}
if let Some(start) = region_to_remove {
normal_memory.remove_region(start, start + initial_objects_size);
} else {
panic!("Couldn't find appropriate region for initial task kernel objects");
}
let fixed_cap_count = 0x10;
let sched_control_cap_count = 1;
let paging_cap_count = get_arch_n_paging(config, initial_task_virt_region);
let page_cap_count = initial_task_virt_region.size() / config.minimum_page_size;
let first_untyped_cap =
fixed_cap_count + paging_cap_count + sched_control_cap_count + page_cap_count;
let sched_control_cap = fixed_cap_count + paging_cap_count;
let max_bits = match config.arch {
Arch::Aarch64 => 47,
Arch::Riscv64 => 38,
};
let device_regions: Vec<MemoryRegion> = [
reserved_region.aligned_power_of_two_regions(max_bits),
device_memory.aligned_power_of_two_regions(max_bits),
]
.concat();
let normal_regions: Vec<MemoryRegion> = [
boot_region.aligned_power_of_two_regions(max_bits),
normal_memory.aligned_power_of_two_regions(max_bits),
]
.concat();
let mut untyped_objects = Vec::new();
for (i, r) in device_regions.iter().enumerate() {
let cap = i as u64 + first_untyped_cap;
untyped_objects.push(UntypedObject::new(cap, *r, true));
}
let normal_regions_start_cap = first_untyped_cap + device_regions.len() as u64;
for (i, r) in normal_regions.iter().enumerate() {
let cap = i as u64 + normal_regions_start_cap;
untyped_objects.push(UntypedObject::new(cap, *r, false));
}
let first_available_cap =
first_untyped_cap + device_regions.len() as u64 + normal_regions.len() as u64;
BootInfo {
fixed_cap_count,
paging_cap_count,
page_cap_count,
sched_control_cap,
first_available_cap,
untyped_objects,
}
}
fn build_system(
config: &Config,
pd_elf_files: &Vec<ElfFile>,
kernel_elf: &ElfFile,
monitor_elf: &ElfFile,
system: &SystemDescription,
invocation_table_size: u64,
system_cnode_size: u64,
) -> Result<BuiltSystem, String> {
assert!(util::is_power_of_two(system_cnode_size));
assert!(invocation_table_size % config.minimum_page_size == 0);
assert!(invocation_table_size <= MAX_SYSTEM_INVOCATION_SIZE);
let mut cap_address_names: HashMap<u64, String> = HashMap::new();
cap_address_names.insert(INIT_NULL_CAP_ADDRESS, "null".to_string());
cap_address_names.insert(INIT_TCB_CAP_ADDRESS, "TCB: init".to_string());
cap_address_names.insert(INIT_CNODE_CAP_ADDRESS, "CNode: init".to_string());
cap_address_names.insert(INIT_VSPACE_CAP_ADDRESS, "VSpace: init".to_string());
cap_address_names.insert(INIT_ASID_POOL_CAP_ADDRESS, "ASID Pool: init".to_string());
cap_address_names.insert(IRQ_CONTROL_CAP_ADDRESS, "IRQ Control".to_string());
cap_address_names.insert(SMC_CAP_IDX, "SMC".to_string());
let system_cnode_bits = system_cnode_size.ilog2() as u64;
// Emulate kernel boot
// Determine physical memory region used by the monitor
let initial_task_size = phys_mem_region_from_elf(monitor_elf, config.minimum_page_size).size();
// Determine physical memory region for 'reserved' memory.
//
// The 'reserved' memory region will not be touched by seL4 during boot
// and allows the monitor (initial task) to create memory regions
// from this area, which can then be made available to the appropriate
// protection domains
let mut pd_elf_size = 0;
for pd_elf in pd_elf_files {
for r in phys_mem_regions_from_elf(pd_elf, config.minimum_page_size) {
pd_elf_size += r.size();
}
}
let reserved_size = invocation_table_size + pd_elf_size;
// Now that the size is determined, find a free region in the physical memory
// space.
let (mut available_memory, kernel_boot_region) =
emulate_kernel_boot_partial(config, kernel_elf);
// The kernel relies on the reserved region being allocated above the kernel
// boot/ELF region, so we have the end of the kernel boot region as the lower
// bound for allocating the reserved region.
let reserved_base = available_memory.allocate_from(reserved_size, kernel_boot_region.end);
assert!(kernel_boot_region.base < reserved_base);
// The kernel relies on the initial task being allocated above the reserved
// region, so we have the address of the end of the reserved region as the
// lower bound for allocating the initial task.
let initial_task_phys_base =
available_memory.allocate_from(initial_task_size, reserved_base + reserved_size);
assert!(reserved_base < initial_task_phys_base);
let initial_task_phys_region = MemoryRegion::new(
initial_task_phys_base,
initial_task_phys_base + initial_task_size,
);
let initial_task_virt_region = virt_mem_region_from_elf(monitor_elf, config.minimum_page_size);
let reserved_region = MemoryRegion::new(reserved_base, reserved_base + reserved_size);
// Now that the reserved region has been allocated we can determine the specific
// region of physical memory required for the inovcation table itself, and
// all the ELF segments
let invocation_table_region =
MemoryRegion::new(reserved_base, reserved_base + invocation_table_size);
// 1.3 With both the initial task region and reserved region determined the kernel
// boot can be emulated. This provides the boot info information which is needed
// for the next steps
let kernel_boot_info = emulate_kernel_boot(
config,
kernel_elf,
initial_task_phys_region,
initial_task_virt_region,
reserved_region,
);
for ut in &kernel_boot_info.untyped_objects {
let dev_str = if ut.is_device { " (device)" } else { "" };
let ut_str = format!(
"Untyped @ 0x{:x}:0x{:x}{}",
ut.region.base,
ut.region.size(),
dev_str
);
cap_address_names.insert(ut.cap, ut_str);
}
// The kernel boot info allows us to create an allocator for kernel objects
let mut kao = ObjectAllocator::new(&kernel_boot_info);
// 2. Now that the available resources are known it is possible to proceed with the
// monitor task boot strap.
//
// The boot strap of the monitor works in two phases:
//
// 1. Setting up the monitor's CSpace
// 2. Making the system invocation table available in the monitor's address
// space.
// 2.1 The monitor's CSpace consists of two CNodes: a/ the initial task CNode
// which consists of all the fixed initial caps along with caps for the
// object create during kernel bootstrap, and b/ the system CNode, which
// contains caps to all objects that will be created in this process.
// The system CNode is of `system_cnode_size`. (Note: see also description
// on how `system_cnode_size` is iteratively determined).
//
// The system CNode is not available at startup and must be created (by retyping
// memory from an untyped object). Once created the two CNodes must be aranged
// as a tree such that the slots in both CNodes are addressable.
//
// The system CNode shall become the root of the CSpace. The initial CNode shall
// be copied to slot zero of the system CNode. In this manner all caps in the initial
// CNode will keep their original cap addresses. This isn't required but it makes
// allocation, debugging and reasoning about the system more straight forward.
//