This repository was archived by the owner on Jul 17, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathprocess.rs
More file actions
1387 lines (1217 loc) · 47.8 KB
/
process.rs
File metadata and controls
1387 lines (1217 loc) · 47.8 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 © 2021 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT
use alloc::boxed::Box;
use alloc::collections::TryReserveError;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::arch::asm;
use core::cell::RefCell;
use core::cmp::PartialEq;
use core::iter::Iterator;
use core::{fmt, ptr};
use arrayvec::ArrayVec;
use fallible_collections::try_vec;
use fallible_collections::FallibleVec;
use kpi::arch::SaveArea;
use kpi::process::{FrameId, ELF_OFFSET, EXECUTOR_OFFSET};
use lazy_static::lazy_static;
use log::{debug, info, trace, warn};
use node_replication::{Dispatch, Log, Replica};
use x86::bits64::paging::*;
use x86::bits64::rflags;
use x86::{controlregs, Ring};
use crate::arch::kcb::per_core_mem;
use crate::error::{KError, KResult};
use crate::fs::{fd::FileDescriptorEntry, MAX_FILES_PER_PROCESS};
use crate::memory::detmem::DA;
use crate::memory::vspace::{AddressSpace, MapAction};
use crate::memory::{paddr_to_kernel_vaddr, Frame, KernelAllocator, MemType, PAddr, VAddr};
use crate::nrproc::NrProcess;
use crate::process::{
Eid, Executor, Pid, Process, ResumeHandle, MAX_FRAMES_PER_PROCESS, MAX_PROCESSES,
MAX_WRITEABLE_SECTIONS_PER_PROCESS,
};
use crate::round_up;
use super::gdt::GdtTable;
use super::vspace::*;
use super::Module;
use super::MAX_NUMA_NODES;
const INVALID_EXECUTOR_START: VAddr = VAddr(0xdeadffff);
/// The process model of the current architecture.
pub(crate) type ArchProcess = Ring3Process;
/// A handle to the currently active (scheduled on the core) process.
#[thread_local]
pub(crate) static CURRENT_EXECUTOR: RefCell<Option<Box<Ring3Executor>>> = RefCell::new(None);
/// Swaps out current process with a new process. Returns the old process.
pub(crate) fn swap_current_executor(
new_executor: Box<Ring3Executor>,
) -> Option<Box<Ring3Executor>> {
CURRENT_EXECUTOR.borrow_mut().replace(new_executor)
}
pub(crate) fn has_executor() -> bool {
CURRENT_EXECUTOR.borrow().is_some()
}
pub(crate) fn current_pid() -> KResult<Pid> {
Ok(CURRENT_EXECUTOR
.borrow()
.as_ref()
.ok_or(KError::ProcessNotSet)?
.pid)
}
lazy_static! {
pub(crate) static ref PROCESS_TABLE: ArrayVec<ArrayVec<Arc<Replica<'static, NrProcess<Ring3Process>>>, MAX_PROCESSES>, MAX_NUMA_NODES> = {
// Want at least one replica...
let numa_nodes = core::cmp::max(1, atopology::MACHINE_TOPOLOGY.num_nodes());
let mut numa_cache = ArrayVec::new();
for _n in 0..numa_nodes {
let process_replicas = ArrayVec::new();
debug_assert!(!numa_cache.is_full());
numa_cache.push(process_replicas)
}
for pid in 0..MAX_PROCESSES {
let log = Arc::try_new(Log::<<NrProcess<Ring3Process> as Dispatch>::WriteOperation>::new(
LARGE_PAGE_SIZE,
)).expect("Can't initialize processes, out of memory.");
let da = DA::new().expect("Can't initialize process deterministic memory allocator");
for node in 0..numa_nodes {
let pcm = per_core_mem();
pcm.set_mem_affinity(node as atopology::NodeId).expect("Can't change affinity");
debug_assert!(!numa_cache[node].is_full());
let p = Box::try_new(Ring3Process::new(pid, da.clone()).expect("Can't create process during init")).expect("Not enough memory to initialize processes");
let nrp = NrProcess::new(p, da.clone());
numa_cache[node].push(Replica::<NrProcess<Ring3Process>>::with_data(&log, nrp));
debug_assert_eq!(*crate::environment::NODE_ID, 0, "Expect initialization to happen on node 0.");
pcm.set_mem_affinity(0 as atopology::NodeId).expect("Can't change affinity");
}
}
numa_cache
};
}
pub(crate) struct ArchProcessManagement;
impl crate::nrproc::ProcessManager for ArchProcessManagement {
type Process = Ring3Process;
fn process_table(
&self,
) -> &'static ArrayVec<
ArrayVec<Arc<Replica<'static, NrProcess<Self::Process>>>, MAX_PROCESSES>,
MAX_NUMA_NODES,
> {
&*super::process::PROCESS_TABLE
}
}
/// Runs a closure `f` while the current core has access to user-space enabled.
///
/// Access is disabled again after `f` returns.
pub(crate) fn with_user_space_access_enabled<F, R>(f: F) -> KResult<R>
where
F: FnOnce() -> KResult<R>,
{
unsafe {
// Safety:
// - SMAP/SMEP is enabled by the bootloader
// - We are in Ring0
rflags::stac();
};
let r = f();
unsafe {
// Safety:
// - SMAP/SMEP is enabled by the bootloader
// - We are in Ring0
rflags::clac();
}
r
}
/// Resume the state saved in `SaveArea` using the `iretq` instruction.
///
/// # Safety
/// Pretty unsafe low-level API that switches to an arbitrary
/// context/instruction pointer. Caller should make sure that `state` is
/// "valid", meaning is an alive context that has not already been resumed.
pub(crate) struct Ring0Resumer {
pub save_area: *const kpi::arch::SaveArea,
}
impl Ring0Resumer {
pub(crate) fn new_iret(save_area: *const kpi::arch::SaveArea) -> Ring0Resumer {
Ring0Resumer { save_area }
}
}
impl ResumeHandle for Ring0Resumer {
unsafe fn resume(self) -> ! {
// Re-enable wanted hardware breakpoints on re-entry:
#[cfg(feature = "gdb")]
{
use bit_field::BitField;
use x86::debugregs::Breakpoint;
let enabled_bps = self.save_area.as_ref().unwrap().enabled_bps;
if enabled_bps.get_bit(0) {
Breakpoint::Dr0.enable_global();
}
if enabled_bps.get_bit(1) {
Breakpoint::Dr1.enable_global();
}
if enabled_bps.get_bit(2) {
Breakpoint::Dr2.enable_global();
}
if enabled_bps.get_bit(3) {
Breakpoint::Dr3.enable_global();
}
}
// TODO(code-duplication): Elimiate code duplication for this and Ring3
// iret_restore. Problem is that the `ss` and `cs` register needs to be
// const, alternative take it from save_area but it might not be right
// in there e.g., has kernel cs/ss when we resume to user-space
asm!("
// Restore the gs register
swapgs
// Restore the fs register
movq {fs_offset}(%rdi), %rsi
wrfsbase %rsi
// Restore vector registers
fxrstor {fxsave_offset}(%rdi)
// Restore CPU registers
movq {rax_offset}(%rdi), %rax
movq {rbx_offset}(%rdi), %rbx
movq {rcx_offset}(%rdi), %rcx
movq {rdx_offset}(%rdi), %rdx
movq {rsi_offset}(%rdi), %rsi
// %rdi: Restore last (see below) to preserve `save_area`
movq {rbp_offset}(%rdi), %rbp
// %rsp: Restored through iretq stack set-up
movq {r8_offset}(%rdi), %r8
movq {r9_offset}(%rdi), %r9
movq {r10_offset}(%rdi), %r10
movq {r11_offset}(%rdi), %r11
movq {r12_offset}(%rdi), %r12
movq {r13_offset}(%rdi), %r13
movq {r14_offset}(%rdi), %r14
movq {r15_offset}(%rdi), %r15
//
// Establish stack frame for iretq: [ss, rsp, rflags, cs, rip]
//
// ss register
pushq ${ss}
// %rsp register
pushq {rsp_offset}(%rdi)
// rflags register
pushq {rflags_offset}(%rdi)
// cs register
pushq ${cs}
// %rip
pushq {rip_offset}(%rdi)
// Restore rdi register last, since it was used to reach `state`
movq {rdi_offset}(%rdi), %rdi
iretq
",
rax_offset = const SaveArea::RAX_OFFSET,
rbx_offset = const SaveArea::RBX_OFFSET,
rcx_offset = const SaveArea::RCX_OFFSET,
rdx_offset = const SaveArea::RDX_OFFSET,
rsi_offset = const SaveArea::RSI_OFFSET,
rdi_offset = const SaveArea::RDI_OFFSET,
rbp_offset = const SaveArea::RBP_OFFSET,
rsp_offset = const SaveArea::RSP_OFFSET,
r8_offset = const SaveArea::R8_OFFSET,
r9_offset = const SaveArea::R9_OFFSET,
r10_offset = const SaveArea::R10_OFFSET,
r11_offset = const SaveArea::R11_OFFSET,
r12_offset = const SaveArea::R12_OFFSET,
r13_offset = const SaveArea::R13_OFFSET,
r14_offset = const SaveArea::R14_OFFSET,
r15_offset = const SaveArea::R15_OFFSET,
rip_offset = const SaveArea::RIP_OFFSET,
rflags_offset = const SaveArea::RFLAGS_OFFSET,
fs_offset = const SaveArea::FS_OFFSET,
fxsave_offset = const SaveArea::FXSAVE_OFFSET,
cs = const GdtTable::kernel_cs_selector().bits(),
ss = const GdtTable::kernel_ss_selector().bits(),
in("rdi") self.save_area,
options(att_syntax, noreturn));
}
}
/// A Ring3Resumer that can either be an upcall or a context restore.
///
/// # TODO
/// This two should ideally be separate with a common resume trait once impl Trait
/// is flexible enough.
/// The interface is not really safe at the moment (we use it in very restricted ways
/// i.e., get the handle and immediatle resume but we can def. make this more safe
/// to use...)
pub(crate) struct Ring3Resumer {
typ: ResumeStrategy,
pub save_area: *const kpi::arch::SaveArea,
entry_point: VAddr,
stack_top: VAddr,
cpu_ctl: u64,
vector: u64,
exception: u64,
}
impl ResumeHandle for Ring3Resumer {
unsafe fn resume(self) -> ! {
match self.typ {
ResumeStrategy::Start => self.start(),
ResumeStrategy::Upcall => self.upcall(),
ResumeStrategy::SysRet => self.restore(),
ResumeStrategy::IRet => self.iret_restore(),
}
}
}
#[derive(Eq, PartialEq, Debug)]
enum ResumeStrategy {
Start,
SysRet,
IRet,
Upcall,
}
impl Ring3Resumer {
pub(crate) fn new_iret(save_area: *const kpi::arch::SaveArea) -> Ring3Resumer {
Ring3Resumer {
typ: ResumeStrategy::IRet,
save_area: save_area,
entry_point: VAddr::zero(),
stack_top: VAddr::zero(),
cpu_ctl: 0,
vector: 0,
exception: 0,
}
}
pub(crate) fn new_restore(save_area: *const kpi::arch::SaveArea) -> Ring3Resumer {
Ring3Resumer {
typ: ResumeStrategy::SysRet,
save_area: save_area,
entry_point: VAddr::zero(),
stack_top: VAddr::zero(),
cpu_ctl: 0,
vector: 0,
exception: 0,
}
}
pub(crate) fn new_upcall(
entry_point: VAddr,
stack_top: VAddr,
cpu_ctl: u64,
vector: u64,
exception: u64,
) -> Ring3Resumer {
Ring3Resumer {
typ: ResumeStrategy::Upcall,
save_area: ptr::null(),
entry_point,
stack_top,
cpu_ctl,
vector,
exception,
}
}
pub(crate) fn new_start(entry_point: VAddr, stack_top: VAddr) -> Ring3Resumer {
Ring3Resumer {
typ: ResumeStrategy::Start,
save_area: ptr::null(),
entry_point,
stack_top,
cpu_ctl: 0,
vector: 0,
exception: 0,
}
}
unsafe fn iret_restore(self) -> ! {
asm!("
// Restore the gs register
swapgs
// Restore the fs register
movq {fs_offset}(%rdi), %rsi
wrfsbase %rsi
// Restore vector registers
fxrstor {fxsave_offset}(%rdi)
// Restore CPU registers
movq {rax_offset}(%rdi), %rax
movq {rbx_offset}(%rdi), %rbx
movq {rcx_offset}(%rdi), %rcx
movq {rdx_offset}(%rdi), %rdx
movq {rsi_offset}(%rdi), %rsi
// %rdi: Restore last (see below) to preserve `save_area`
movq {rbp_offset}(%rdi), %rbp
// %rsp: Restored through iretq stack set-up
movq {r8_offset}(%rdi), %r8
movq {r9_offset}(%rdi), %r9
movq {r10_offset}(%rdi), %r10
movq {r11_offset}(%rdi), %r11
movq {r12_offset}(%rdi), %r12
movq {r13_offset}(%rdi), %r13
movq {r14_offset}(%rdi), %r14
movq {r15_offset}(%rdi), %r15
//
// Establish stack frame for iretq: [ss, rsp, rflags, cs, rip]
//
// ss register
pushq ${ss}
// %rsp register
pushq {rsp_offset}(%rdi)
// rflags register
pushq {rflags_offset}(%rdi)
// cs register
pushq ${cs}
// %rip
pushq {rip_offset}(%rdi)
// Restore rdi register last, since it was used to reach `state`
movq {rdi_offset}(%rdi), %rdi
iretq
",
rax_offset = const SaveArea::RAX_OFFSET,
rbx_offset = const SaveArea::RBX_OFFSET,
rcx_offset = const SaveArea::RCX_OFFSET,
rdx_offset = const SaveArea::RDX_OFFSET,
rsi_offset = const SaveArea::RSI_OFFSET,
rdi_offset = const SaveArea::RDI_OFFSET,
rbp_offset = const SaveArea::RBP_OFFSET,
rsp_offset = const SaveArea::RSP_OFFSET,
r8_offset = const SaveArea::R8_OFFSET,
r9_offset = const SaveArea::R9_OFFSET,
r10_offset = const SaveArea::R10_OFFSET,
r11_offset = const SaveArea::R11_OFFSET,
r12_offset = const SaveArea::R12_OFFSET,
r13_offset = const SaveArea::R13_OFFSET,
r14_offset = const SaveArea::R14_OFFSET,
r15_offset = const SaveArea::R15_OFFSET,
rip_offset = const SaveArea::RIP_OFFSET,
rflags_offset = const SaveArea::RFLAGS_OFFSET,
fs_offset = const SaveArea::FS_OFFSET,
fxsave_offset = const SaveArea::FXSAVE_OFFSET,
cs = const GdtTable::user_cs_selector().bits(),
ss = const GdtTable::user_ss_selector().bits(),
in("rdi") self.save_area,
options(att_syntax, noreturn));
}
unsafe fn restore(self) -> ! {
let user_rflags = rflags::RFlags::from_priv(Ring::Ring3)
| rflags::RFlags::FLAGS_A1
| rflags::RFlags::FLAGS_IF;
//info!("resuming User-space with ctxt: {:?}", (*(self.save_area)),);
// Resumes a process
// This routine assumes the following set-up
// %rdi points to SaveArea
// r11 has rflags
asm!("
// Restore CPU registers
movq {rax_offset}(%rdi), %rax
movq {rbx_offset}(%rdi), %rbx
// %rcx: Don't restore it will contain user-space rip
movq {rdx_offset}(%rdi), %rdx
// %rdi and %rsi: Restore last (see below) to preserve `save_area`
movq {rbp_offset}(%rdi), %rbp
movq {rsp_offset}(%rdi), %rsp
movq {r8_offset}(%rdi), %r8
movq {r9_offset}(%rdi), %r9
movq {r10_offset}(%rdi), %r10
// %r11: Don't restore it will contain RFlags
movq {r12_offset}(%rdi), %r12
movq {r13_offset}(%rdi), %r13
movq {r14_offset}(%rdi), %r14
movq {r15_offset}(%rdi), %r15
// Restore fs and gs registers
swapgs
movq {fs_offset}(%rdi), %rsi
wrfsbase %rsi
// Restore vector registers
fxrstor {fxsave_offset}(%rdi)
// sysretq expects user-space %rip in %rcx
movq {rip_offset}(%rdi),%rcx
// sysretq expects rflags in %r11
// At last, restore %rsi and %rdi before we return
movq {rsi_offset}(%rdi), %rsi
movq {rdi_offset}(%rdi), %rdi
sysretq
",
rax_offset = const SaveArea::RAX_OFFSET,
rbx_offset = const SaveArea::RBX_OFFSET,
rdx_offset = const SaveArea::RDX_OFFSET,
rsi_offset = const SaveArea::RSI_OFFSET,
rdi_offset = const SaveArea::RDI_OFFSET,
rbp_offset = const SaveArea::RBP_OFFSET,
rsp_offset = const SaveArea::RSP_OFFSET,
r8_offset = const SaveArea::R8_OFFSET,
r9_offset = const SaveArea::R9_OFFSET,
r10_offset = const SaveArea::R10_OFFSET,
r12_offset = const SaveArea::R12_OFFSET,
r13_offset = const SaveArea::R13_OFFSET,
r14_offset = const SaveArea::R14_OFFSET,
r15_offset = const SaveArea::R15_OFFSET,
rip_offset = const SaveArea::RIP_OFFSET,
fs_offset = const SaveArea::FS_OFFSET,
fxsave_offset = const SaveArea::FXSAVE_OFFSET,
in("rdi") self.save_area,
in("r11") user_rflags.bits(),
options(att_syntax, noreturn)
);
}
unsafe fn upcall(self) -> ! {
trace!("About to go to user-space: {:#x}", self.entry_point);
// TODO(safety): For now we allow unconditional IO access from user-space
let user_flags =
rflags::RFlags::FLAGS_IOPL3 | rflags::RFlags::FLAGS_A1 | rflags::RFlags::FLAGS_IF;
// Switch to user-space with initial zeroed registers.
//
// Stack is set to the initial stack for the process that
// was allocated by the kernel.
//
// `sysretq` expectations are:
// %rcx Program entry point in Ring 3
// %r11 RFlags
trace!("Jumping to {:#x}", self.entry_point);
asm!("
// rax: contains stack pointer
movq $0, %rbx
// rcx: has entry point
// rdi: 1st argument
// rsi: 2nd argument
// rdx: 3rd argument
// rsp and rbp are set to provided `stack_top`
movq $0, %r8
movq $0, %r9
movq $0, %r10
// r11 register is used for RFlags
movq $0, %r12
movq $0, %r13
movq $0, %r14
movq $0, %r15
// Reset vector registers
fninit
swapgs
// TODO: restore fs register
movq %rax, %rbp
movq %rax, %rsp
sysretq
",
in("rcx") self.entry_point.as_u64(),
in("rdi") self.cpu_ctl,
in("rsi") self.vector,
in("rdx") self.exception,
in("rax") self.stack_top.as_u64(),
in("r11") user_flags.bits(),
options(att_syntax, noreturn)
);
}
unsafe fn start(self) -> ! {
trace!("About to go to user-space: {:#x}", self.entry_point);
warn!("Make sure IA32_KERNEL_GSBASE still points to KCB!");
// TODO: For now we allow unconditional IO access from user-space
let user_flags =
rflags::RFlags::FLAGS_IOPL3 | rflags::RFlags::FLAGS_A1 | rflags::RFlags::FLAGS_IF;
// Switch to user-space with initial zeroed registers.
//
// Stack is set to the initial stack for the process that
// was allocated by the kernel.
//
// `sysretq` expectations are:
// %rcx Program entry point in Ring 3
// %r11 RFlags
trace!("Jumping to {:#x}", self.entry_point);
asm!("
// rax: contains stack pointer
movq $0, %rbx
// rcx: has entry point
// rdi: 1st argument
// rsi: 2nd argument
// rdx: 3rd argument
// rsp and rbp are set to provided `stack_top`
movq $0, %r8
movq $0, %r9
movq $0, %r10
// r11 register is used for RFlags
movq $0, %r12
movq $0, %r13
movq $0, %r14
movq $0, %r15
// Reset vector registers
fninit
// Set gs and fs to 0
wrgsbase %r15
wrfsbase %r15
movq %rax, %rbp
movq %rax, %rsp
sysretq
",
in("rcx") self.entry_point.as_u64(),
in("rdi") self.cpu_ctl,
in("rsi") self.vector,
in("rdx") self.exception,
in("rax") self.stack_top.as_u64(),
in("r11") user_flags.bits(),
options(att_syntax, noreturn)
);
}
}
/// An executor is a thread running in a ring 3 in the context
/// (address-space) of a specific process.
///
/// # Notes
/// repr(C): Because `save_area` in is struct is written to from assembly
/// (and therefore should be first).
#[derive(Copy, Clone, Debug)]
#[repr(C)]
pub(crate) struct Ring3Executor {
/// CPU context save area (must be first, see exec.S).
pub save_area: kpi::x86_64::SaveArea,
/// Allocated stack (base address).
pub stack_base: VAddr,
/// Up-call stack (base address).
pub upcall_stack_base: VAddr,
/// Process identifier
pub pid: Pid,
/// Executor Identifier
pub eid: Eid,
/// Memory affinity of the Executor
pub affinity: atopology::NodeId,
/// Virtual CPU control used by the user-space upcall mechanism.
pub vcpu_ctl: VAddr,
/// Alias to `vcpu_ctl` but accessible in kernel space.
pub vcpu_ctl_kernel: VAddr,
/// Entry point where the executor should start executing from
///
/// Usually an ELF start point (for the first dispatcher) then somthing set
/// by the process after.
///
/// e.g. in process this can be computed as self.offset + self.entry_point
pub entry_point: VAddr,
/// A handle to the vspace PML4 entry point.
pub pml4: PAddr,
}
// CPU context save area (must be first, see exec.S)
static_assertions::const_assert_eq!(memoffset::offset_of!(Ring3Executor, save_area), 0);
impl PartialEq<Ring3Executor> for Ring3Executor {
fn eq(&self, other: &Ring3Executor) -> bool {
self.pid == other.pid && self.eid == other.eid
}
}
impl Ring3Executor {
/// Size of the init stack (i.e., initial stack when the dispatcher starts running).
const INIT_STACK_SIZE: usize = 24 * BASE_PAGE_SIZE;
/// Size of the upcall signal stack for the dispatcher.
const UPCALL_STACK_SIZE: usize = 24 * BASE_PAGE_SIZE;
/// Total memory consumption (in a process' vspace) that the executor uses.
/// (2 stacks plus the VirtualCpu struct.)
const EXECUTOR_SPACE_REQUIREMENT: usize =
Ring3Executor::INIT_STACK_SIZE + Ring3Executor::UPCALL_STACK_SIZE + BASE_PAGE_SIZE;
fn new(
process: &Ring3Process,
eid: Eid,
vcpu_ctl_kernel: VAddr,
region: (VAddr, VAddr),
affinity: atopology::NodeId,
) -> Self {
let (from, to) = region;
assert!(to > from, "Malformed region");
assert!(
(to - from).as_usize()
>= Ring3Executor::INIT_STACK_SIZE
+ Ring3Executor::UPCALL_STACK_SIZE
+ core::mem::size_of::<kpi::arch::VirtualCpu>(),
"Virtual region not big enough"
);
let stack_base = from;
let upcall_stack_base = from + Ring3Executor::INIT_STACK_SIZE;
let vcpu_vaddr: VAddr =
from + Ring3Executor::INIT_STACK_SIZE + Ring3Executor::UPCALL_STACK_SIZE;
Ring3Executor {
stack_base,
upcall_stack_base,
pid: process.pid,
eid,
affinity,
vcpu_ctl_kernel,
vcpu_ctl: vcpu_vaddr,
save_area: Default::default(),
entry_point: process.offset + process.entry_point,
// Note: The PML4 is a bit awkward here, we must ensure to use the
// PML4 of the local replica, but aside from some asserts in
// `start`, `resume` etc. nothing prevents us from running this
// executor on a different replica (which means the advance log on
// pfault would not really advance the right set of page-tables)
pml4: process.vspace.pml4_address(),
}
}
/// Get access to the executors' vcpu area.
///
/// # Safety
/// - Caller needs to ensure it doesn't accidentially create two mutable
/// aliasable pointers to the same memory.
/// - TODO(api): A safer API for this might be appreciated.
pub(crate) fn vcpu(&self) -> &mut kpi::arch::VirtualCpu {
unsafe { &mut *self.vcpu_ctl_kernel.as_mut_ptr() }
}
pub(crate) fn vcpu_addr(&self) -> VAddr {
self.vcpu_ctl
}
fn stack_top(&self) -> VAddr {
// -8 due to x86 stack alignemnt requirements
self.stack_base + Ring3Executor::INIT_STACK_SIZE - 8usize
}
fn upcall_stack_top(&self) -> VAddr {
// -8 due to x86 stack alignemnt requirements
self.upcall_stack_base + Ring3Executor::UPCALL_STACK_SIZE - 8usize
}
}
impl fmt::Display for Ring3Executor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Ring3Executor {}", self.eid)
}
}
impl Executor for Ring3Executor {
type Resumer = Ring3Resumer;
fn id(&self) -> Eid {
self.eid
}
fn pid(&self) -> Pid {
self.pid
}
fn vcpu_kernel(&self) -> *mut kpi::arch::VirtualCpu {
self.vcpu_ctl_kernel.as_mut_ptr()
}
/// Start the process (run it for the first time).
fn start(&self) -> Self::Resumer {
assert_eq!(
*crate::environment::NODE_ID,
self.affinity,
"Run on remote replica?"
);
self.maybe_switch_vspace();
let entry_point = unsafe { (*self.vcpu_kernel()).resume_with_upcall };
if entry_point == INVALID_EXECUTOR_START {
Ring3Resumer::new_start(self.entry_point, self.stack_top())
} else {
// This is similar to `upcall` as it starts executing the defined upcall
// handler, but on the regular stack (for that dispatcher) and not
// the upcall stack. It's used to add a new core to a process.
let entry_point = unsafe { (*self.vcpu_kernel()).resume_with_upcall };
trace!("Added core entry point is at {:#x}", entry_point);
let cpu_ctl = self.vcpu_addr().as_u64();
Ring3Resumer::new_upcall(
entry_point,
self.stack_top(),
cpu_ctl,
kpi::upcall::NEW_CORE,
*crate::environment::CORE_ID as u64,
)
}
}
fn resume(&self) -> Self::Resumer {
assert_eq!(
*crate::environment::NODE_ID,
self.affinity,
"Run on remote replica?"
);
self.maybe_switch_vspace();
Ring3Resumer::new_restore(&self.save_area as *const kpi::arch::SaveArea)
}
fn upcall(&self, vector: u64, exception: u64) -> Self::Resumer {
assert_eq!(
*crate::environment::NODE_ID,
self.affinity,
"Run on remote replica?"
);
self.maybe_switch_vspace();
let entry_point = self.vcpu().resume_with_upcall;
let cpu_ctl = self.vcpu_addr().as_u64();
Ring3Resumer::new_upcall(
entry_point,
self.upcall_stack_top(),
cpu_ctl,
vector,
exception,
)
}
fn maybe_switch_vspace(&self) {
unsafe {
let current_pml4 = PAddr::from(controlregs::cr3());
if current_pml4 != self.pml4 {
trace!("Switching to 0x{:x}", self.pml4);
controlregs::cr3_write(self.pml4.into());
}
}
}
}
/// A process representation.
pub(crate) struct Ring3Process {
/// Ring3Process ID.
pub pid: Pid,
/// Ring3Executor ID.
pub current_eid: Eid,
/// The address space of the process.
pub vspace: VSpace,
/// Offset where ELF is located.
pub offset: VAddr,
/// Process info struct (can be retrieved by user-space)
pub pinfo: kpi::process::ProcessInfo,
/// The entry point of the ELF file (set during elfloading).
pub entry_point: VAddr,
/// Executor cache (holds a per-region cache of executors)
pub executor_cache: ArrayVec<Option<Vec<Box<Ring3Executor>>>, MAX_NUMA_NODES>,
/// Offset where executor memory is located in user-space.
pub executor_offset: VAddr,
/// File descriptors for the opened file.
pub fds: ArrayVec<Option<FileDescriptorEntry>, MAX_FILES_PER_PROCESS>,
/// Physical frame objects registered to the process.
pub frames: ArrayVec<Option<Frame>, MAX_FRAMES_PER_PROCESS>,
/// Frames of the writeable ELF data section (shared across all replicated Process structs)
pub writeable_sections: ArrayVec<Frame, MAX_WRITEABLE_SECTIONS_PER_PROCESS>,
/// Section in ELF where last read-only header is
///
/// (TODO(robustness): assumes that all read-only segments come before
/// writable segments).
pub read_only_offset: VAddr,
}
impl Ring3Process {
fn new(pid: Pid, da: DA) -> Result<Self, KError> {
const NONE_EXECUTOR: Option<Vec<Box<Ring3Executor>>> = None;
let executor_cache: ArrayVec<Option<Vec<Box<Ring3Executor>>>, MAX_NUMA_NODES> =
ArrayVec::from([NONE_EXECUTOR; MAX_NUMA_NODES]);
const NONE_FD: Option<FileDescriptorEntry> = None;
let fds: ArrayVec<Option<FileDescriptorEntry>, MAX_FILES_PER_PROCESS> =
ArrayVec::from([NONE_FD; MAX_FILES_PER_PROCESS]);
let frames: ArrayVec<Option<Frame>, MAX_FRAMES_PER_PROCESS> =
ArrayVec::from([None; MAX_FRAMES_PER_PROCESS]);
Ok(Ring3Process {
pid: pid,
current_eid: 0,
offset: VAddr::from(ELF_OFFSET),
vspace: VSpace::new(da)?,
entry_point: VAddr::from(0usize),
executor_cache,
executor_offset: VAddr::from(EXECUTOR_OFFSET),
fds,
pinfo: Default::default(),
frames,
writeable_sections: ArrayVec::new(),
read_only_offset: VAddr::zero(),
})
}
}
impl fmt::Debug for Ring3Process {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Ring3Process {}", self.pid)
}
}
impl elfloader::ElfLoader for Ring3Process {
/// Makes sure the process' vspace is backed for the regions
/// reported by the ELF loader as loadable.
///
/// Our strategy is to first figure out how much space we need,
/// then allocate a single chunk of physical memory and
/// map the individual pieces of it with different access rights.
/// This has the advantage that our address space is
/// all a very simple 1:1 mapping of physical memory.
fn allocate(
&mut self,
load_headers: elfloader::LoadableHeaders,
) -> Result<(), elfloader::ElfLoaderErr> {
for header in load_headers.into_iter() {
let base = header.virtual_addr();
let size = header.mem_size() as usize;
let align_to = header.align();
let flags = header.flags();
// Calculate the offset and align to page boundaries
// We can't expect to get something that is page-aligned from ELF
let page_mask = (LARGE_PAGE_SIZE - 1) as u64;
let page_base: VAddr = VAddr::from(base & !page_mask); // Round down to nearest page-size
let size_page = round_up!(size + (base & page_mask) as usize, LARGE_PAGE_SIZE as usize);
assert!(size_page >= size);
assert_eq!(size_page % LARGE_PAGE_SIZE, 0);
assert_eq!(page_base % LARGE_PAGE_SIZE, 0);
let map_action = match (flags.is_execute(), flags.is_write(), flags.is_read()) {
(false, false, false) => panic!("MapAction::None"),
(true, false, false) => panic!("MapAction::None"),
(false, true, false) => panic!("MapAction::None"),
(false, false, true) => MapAction::ReadUser,
(true, false, true) => MapAction::ReadExecuteUser,
(true, true, false) => panic!("MapAction::None"),
(false, true, true) => MapAction::ReadWriteUser,
(true, true, true) => MapAction::ReadWriteExecuteUser,
};
info!(
"ELF Allocate: {:#x} -- {:#x} align to {:#x} with flags {:?} ({:?})",
page_base,
page_base + size_page,
align_to,
flags,
map_action
);
let large_pages = size_page / LARGE_PAGE_SIZE;
debug!("page_base {} lps: {}", page_base, large_pages);
// TODO(correctness): add 20 as estimate of worst case pt requirements
KernelAllocator::try_refill_tcache(20, large_pages, MemType::Mem)
.expect("Refill didn't work");
let pcm = crate::arch::kcb::per_core_mem();
// TODO(correctness): Will this work (we round-up and map large-pages?)
// TODO(efficiency): What about wasted memory
// TODO(hard-coded replication assumptions): We assume that we only have 1 data section
// that is read-write and that fits within data_frame (so replication works out)
// We should probably return an error and request more bigger data frames if what
// we provide initially doesn't work out...
let mut wsection_idx = 0;
for i in 0..large_pages {
let frame = if flags.is_write() {
// Writeable program-headers we can't replicate:
assert!(
wsection_idx < self.writeable_sections.len(),
"Didn't pass enough frames for writeable sections to process create."
);
assert_eq!(
self.writeable_sections[wsection_idx].size(),
LARGE_PAGE_SIZE,
"We expect writeable sections frame to be a large-page."
);
let frame = self.writeable_sections[wsection_idx];
wsection_idx += 1;
frame
} else {
// A read-only program header we can replicate:
assert!(
map_action == MapAction::ReadUser
|| map_action == MapAction::ReadExecuteUser
);
let mut pmanager = pcm.mem_manager();
pmanager
.allocate_large_page()
.expect("We refilled so allocation should work.")
};
trace!(
"process load vspace from {:#x} with {:?}",