-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathmain.rs
1515 lines (1372 loc) · 50.1 KB
/
main.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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use std::collections::{BTreeMap, VecDeque};
use std::fmt;
use std::fs::File;
use std::io::{Error, ErrorKind, Result};
use std::path::Path;
use std::process::ExitCode;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::time::{SystemTime, UNIX_EPOCH};
use anyhow::Context;
use clap::Parser;
use futures::future::BoxFuture;
use propolis::hw::qemu::pvpanic::QemuPvpanic;
use propolis_types::{CpuidIdent, CpuidValues, CpuidVendor};
use slog::{o, Drain};
use strum::IntoEnumIterator;
use tokio::runtime;
use propolis::chardev::{BlockingSource, Sink, Source, UDSock};
use propolis::common::{GB, MB};
use propolis::firmware::smbios;
use propolis::hw::chipset::{i440fx, Chipset};
use propolis::hw::ps2::ctrl::PS2Ctrl;
use propolis::hw::qemu::fwcfg;
use propolis::hw::uart::LpcUart;
use propolis::hw::{ibmpc, qemu};
use propolis::intr_pins::FuncPin;
use propolis::usdt::register_probes;
use propolis::vcpu::Vcpu;
use propolis::vmm::{Builder, Machine};
use propolis::*;
mod cidata;
mod config;
mod snapshot;
const PAGE_OFFSET: u64 = 0xfff;
// Arbitrary ROM limit for now
const MAX_ROM_SIZE: usize = 0x20_0000;
const MIN_RT_THREADS: usize = 8;
const BASE_RT_THREADS: usize = 4;
#[derive(Copy, Clone, Debug)]
enum InstEvent {
Halt,
ReqHalt,
Reset,
TripleFault,
ReqSave,
ReqStart,
}
impl InstEvent {
fn priority(&self) -> u8 {
match self {
InstEvent::Halt | InstEvent::ReqHalt => 3,
InstEvent::Reset | InstEvent::TripleFault => 2,
InstEvent::ReqSave => 1,
InstEvent::ReqStart => 0,
}
}
fn supersedes(&self, comp: &Self) -> bool {
self.priority() >= comp.priority()
}
}
impl From<propolis::exits::Suspend> for InstEvent {
fn from(value: propolis::exits::Suspend) -> Self {
match value {
exits::Suspend::Halt => Self::Halt,
exits::Suspend::Reset => Self::Reset,
exits::Suspend::TripleFault(_) => Self::TripleFault,
}
}
}
#[derive(Clone, Debug)]
// Silence the lint about detail fields being unused, since rustc ignores the
// derived Debug impl which does read those bits.
#[allow(dead_code)]
enum EventCtx {
Vcpu(i32),
Pin(String),
User(String),
Other(String),
}
#[derive(Default)]
struct EQInner {
events: VecDeque<(InstEvent, EventCtx)>,
}
#[derive(Default)]
struct EventQueue {
inner: Mutex<EQInner>,
cv: Condvar,
}
impl EventQueue {
fn new() -> Arc<Self> {
Arc::new(Self::default())
}
fn push(&self, ev: InstEvent, ctx: EventCtx) {
let mut inner = self.inner.lock().unwrap();
inner.events.push_back((ev, ctx));
self.cv.notify_one();
}
fn pop_superseding(
&self,
cur: Option<&InstEvent>,
) -> Option<(InstEvent, EventCtx)> {
let mut inner = self.inner.lock().unwrap();
while let Some((ev, ctx)) = inner.events.pop_front() {
match cur {
Some(cur_ev) => {
if cur_ev.supersedes(&ev) {
// queued event is superseded by current one, so discard
// it and look for another which may be relevant.
continue;
} else {
return Some((ev, ctx));
}
}
None => return Some((ev, ctx)),
}
}
None
}
fn wait(&self) {
let guard = self.inner.lock().unwrap();
let _guard = self.cv.wait_while(guard, |g| g.events.is_empty());
}
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum State {
/// Initial state.
Initialize,
/// The instance is actively running.
Run,
/// The instance is in a paused state such that it may
/// later be booted or maintained.
Quiesce,
/// The instance state is being exported
Save,
/// The instance is no longer running
Halt,
/// The instance is rebooting, and should transition back
/// to the "Run" state.
Reset,
/// Terminal state in which the instance is torn down.
Destroy,
}
impl State {
fn next(&self, ev: InstEvent) -> (Self, Option<InstEvent>) {
match self {
State::Initialize => {
if matches!(ev, InstEvent::ReqStart) {
(State::Run, None)
} else {
// All other events require a quiesce first
(State::Quiesce, Some(ev))
}
}
State::Run => {
if matches!(ev, InstEvent::ReqStart) {
// Discard any duplicate start requests when running
(State::Run, None)
} else {
// All other events require a quiesce first
(State::Quiesce, Some(ev))
}
}
State::Quiesce => match ev {
InstEvent::Halt | InstEvent::ReqHalt => (State::Halt, Some(ev)),
InstEvent::Reset | InstEvent::TripleFault => {
(State::Reset, Some(ev))
}
InstEvent::ReqSave => (State::Save, Some(ev)),
InstEvent::ReqStart => {
// Reaching quiesce with a "start" event would be odd
panic!("unexpected ReqStart");
}
},
State::Save => (State::Halt, Some(ev)),
State::Halt => (State::Destroy, None),
State::Reset => match ev {
InstEvent::Halt | InstEvent::ReqHalt => (State::Halt, Some(ev)),
InstEvent::Reset | InstEvent::TripleFault => (State::Run, None),
_ => (State::Run, Some(ev)),
},
State::Destroy => (State::Destroy, None),
}
}
}
#[derive(Default)]
struct Inventory {
devs: BTreeMap<String, Arc<dyn propolis::common::Lifecycle>>,
block: BTreeMap<String, Arc<dyn propolis::block::Backend>>,
}
impl Inventory {
fn register<D: propolis::common::Lifecycle>(&mut self, dev: &Arc<D>) {
self.devs.insert(
dev.type_name().into(),
dev.clone() as Arc<dyn propolis::common::Lifecycle>,
);
}
fn register_instance<D: propolis::common::Lifecycle>(
&mut self,
dev: &Arc<D>,
name: &str,
) {
self.devs.insert(
format!("{}-{name}", dev.type_name()),
dev.clone() as Arc<dyn propolis::common::Lifecycle>,
);
}
fn register_block(
&mut self,
be: &Arc<dyn propolis::block::Backend>,
name: String,
) {
self.block.insert(name, be.clone());
}
fn destroy(&mut self) {
// Detach all block backends from their devices
for backend in self.block.values() {
let _ = backend.attachment().detach();
}
// Drop all refs in the hopes that things can clean up after themselves
self.devs.clear();
self.block.clear();
}
}
struct InstState {
machine: Option<propolis::Machine>,
inventory: Inventory,
state: State,
vcpu_tasks: Vec<propolis::tasks::TaskCtrl>,
exit_code: Option<u8>,
}
struct InstInner {
state: Mutex<InstState>,
boot_gen: AtomicUsize,
eq: Arc<EventQueue>,
cv: Condvar,
config: config::Config,
}
struct Instance(Arc<InstInner>);
impl Instance {
fn new(
machine: propolis::Machine,
config: config::Config,
from_restore: bool,
log: slog::Logger,
) -> Self {
let this = Self(Arc::new(InstInner {
state: Mutex::new(InstState {
machine: Some(machine),
inventory: Inventory::default(),
state: State::Initialize,
vcpu_tasks: Vec::new(),
exit_code: None,
}),
boot_gen: AtomicUsize::new(0),
eq: EventQueue::new(),
cv: Condvar::new(),
config,
}));
// Some gymnastics required for the split borrow through the MutexGuard
let mut state_guard = this.0.state.lock().unwrap();
let state = &mut *state_guard;
let machine = state.machine.as_ref().unwrap();
for vcpu in machine.vcpus.iter().map(Arc::clone) {
let (task, ctrl) =
propolis::tasks::TaskHdl::new_held(Some(vcpu.barrier_fn()));
let inner = this.0.clone();
let task_log = log.new(slog::o!("vcpu" => vcpu.id));
let _ = std::thread::Builder::new()
.name(format!("vcpu-{}", vcpu.id))
.spawn(move || {
Instance::vcpu_loop(inner, vcpu.as_ref(), &task, task_log)
})
.unwrap();
state.vcpu_tasks.push(ctrl);
}
drop(state_guard);
let rt_hdl = runtime::Handle::current();
let inner = this.0.clone();
let state_log = log.clone();
let _ = std::thread::Builder::new()
.name("state loop".to_string())
.spawn(move || {
// Make sure the instance state driver has access to tokio
let _rt_guard = rt_hdl.enter();
Instance::state_loop(inner, from_restore, state_log)
})
.unwrap();
this
}
fn device_state_transition(
state: State,
guard: &MutexGuard<InstState>,
first_boot: bool,
log: &slog::Logger,
) {
for (name, device) in guard.inventory.devs.iter() {
match state {
State::Run => {
if first_boot {
device.start().unwrap_or_else(|_| {
panic!("device {} failed to start", name)
});
} else {
device.resume();
}
}
State::Quiesce => device.pause(),
State::Halt => device.halt(),
State::Reset => device.reset(),
_ => panic!("invalid device state transition {:?}", state),
}
}
if matches!(state, State::Quiesce) {
let tasks: futures::stream::FuturesUnordered<
BoxFuture<'static, ()>,
> = guard
.inventory
.devs
.values()
.map(|device| device.paused())
.collect();
// Wait for all of the pause futures to complete
tokio::runtime::Handle::current().block_on(async move {
use futures::stream::StreamExt;
let _: Vec<()> = tasks.collect().await;
});
}
// Drive block backends through their necessary states too
match state {
State::Run if first_boot => {
tokio::runtime::Handle::current().block_on(async {
for (_name, be) in guard.inventory.block.iter() {
be.start().await.expect("blockdev start succeeds");
}
});
}
State::Halt => {
tokio::runtime::Handle::current().block_on(async {
for (name, be) in guard.inventory.block.iter() {
be.stop().await;
if let Err(err) = be.detach() {
slog::error!(
log,
"Error during detach of block backend {}: {:?}",
name,
err
);
}
}
});
}
_ => {}
}
}
fn state_loop(
inner: Arc<InstInner>,
from_restore: bool,
log: slog::Logger,
) {
let mut guard = inner.state.lock().unwrap();
let mut cur_ev = None;
if !from_restore {
// Initialized vCPUs to standard x86 state, unless this instance is
// being restored from a snapshot, in which case the snapshot state
// will be injected prior to start-up.
let machine = guard.machine.as_ref().unwrap();
machine.vcpu_x86_setup().unwrap();
}
// If instance was restored from previously-saved state, the kernel VMM
// portion will be paused so it could be consistently loaded. Issue the
// necessary resume before attempting to run.
let mut needs_resume = from_restore;
assert!(matches!(guard.state, State::Initialize));
loop {
if let Some((next_ev, ctx)) =
inner.eq.pop_superseding(cur_ev.as_ref())
{
slog::info!(&log, "Instance event {:?} ({:?})", next_ev, ctx);
cur_ev = Some(next_ev);
}
if cur_ev.is_none() {
drop(guard);
inner.eq.wait();
guard = inner.state.lock().unwrap();
continue;
}
let (next_state, resid_ev) = guard.state.next(cur_ev.unwrap());
if guard.state == next_state {
continue;
}
slog::info!(
&log,
"State transition {:?} -> {:?}",
guard.state,
next_state
);
match next_state {
State::Initialize => {
panic!("initialize state should not be visited again")
}
State::Run => {
// start device emulation and vCPUs
Self::device_state_transition(
State::Run,
&guard,
inner.boot_gen.load(Ordering::Acquire) == 0,
&log,
);
if needs_resume {
let machine = guard.machine.as_ref().unwrap();
machine
.hdl
.resume()
.expect("restored instance can resume running");
needs_resume = false;
}
// TODO: bail if any vCPU tasks have exited already
for vcpu_task in guard.vcpu_tasks.iter_mut() {
let _ = vcpu_task.run();
}
}
State::Quiesce => {
// stop device emulation and vCPUs
for vcpu_task in guard.vcpu_tasks.iter_mut() {
let _ = vcpu_task.hold();
}
Self::device_state_transition(
State::Quiesce,
&guard,
false,
&log,
);
let machine = guard.machine.as_ref().unwrap();
machine.hdl.pause().expect("pause should complete");
}
State::Save => {
let guard = &mut *guard;
let save_res = snapshot::save(guard, &inner.config, &log);
if let Err(err) = save_res {
slog::error!(log, "Snapshot error {:?}", err);
}
}
State::Halt => {
Self::device_state_transition(
State::Halt,
&guard,
false,
&log,
);
for mut vcpu_ctrl in guard.vcpu_tasks.drain(..) {
vcpu_ctrl.exit();
}
if guard.exit_code.is_none() {
guard.exit_code = Some(inner.config.main.exit_on_halt);
}
}
State::Reset => {
if let (None, Some(code)) =
(guard.exit_code, inner.config.main.exit_on_reboot)
{
// Emit the configured exit-on-reboot code if one is
// configured an no existing code would already
// supersede it.
guard.exit_code = Some(code);
guard.state = State::Halt;
cur_ev = Some(InstEvent::ReqHalt);
continue;
}
Self::device_state_transition(
State::Reset,
&guard,
false,
&log,
);
let machine = guard.machine.as_ref().unwrap();
machine.reinitialize().unwrap();
machine.vcpu_x86_setup().unwrap();
inner.boot_gen.fetch_add(1, Ordering::Release);
machine.hdl.resume().expect("resume should complete");
}
State::Destroy => {
// Drop the machine
let _ = guard.machine.take().unwrap();
// Clean up the inventory as well
guard.inventory.destroy();
// Communicate that destruction is complete
slog::info!(&log, "Instance destroyed");
guard.state = State::Destroy;
inner.cv.notify_all();
return;
}
}
guard.state = next_state;
cur_ev = resid_ev;
}
}
fn wait_destroyed(&self) -> ExitCode {
let guard = self.0.state.lock().unwrap();
let mut guard = self
.0
.cv
.wait_while(guard, |g| !matches!(g.state, State::Destroy))
.unwrap();
ExitCode::from(guard.exit_code.take().unwrap_or(0))
}
fn vcpu_loop(
inner: Arc<InstInner>,
vcpu: &Vcpu,
task: &propolis::tasks::TaskHdl,
log: slog::Logger,
) {
use propolis::exits::{SuspendDetail, VmExitKind};
use propolis::tasks::Event;
let mut entry = VmEntry::Run;
let mut exit = VmExit::default();
let mut local_gen = 0;
loop {
let mut exit_when_consistent = false;
match task.pending_event() {
Some(Event::Hold) => {
if !exit.kind.is_consistent() {
// Before the vCPU task can enter the held state, its
// associated in-kernel state must be driven to a point
// where it is consistent.
exit_when_consistent = true;
} else {
task.hold();
// Check if the instance was reinitialized while task was held.
let cur_gen = inner.boot_gen.load(Ordering::Acquire);
if local_gen != cur_gen {
// Reset occurred, discard any existing entry details.
entry = VmEntry::Run;
local_gen = cur_gen;
}
continue;
}
}
Some(Event::Exit) => {
return;
}
None => {}
}
exit = match vcpu.run(&entry, exit_when_consistent) {
Err(e) => {
slog::error!(&log, "VM entry error {:?}", e);
inner.eq.push(
InstEvent::Halt,
EventCtx::Other(format!(
"error {:?} on vcpu {}",
e.raw_os_error().unwrap_or(0),
vcpu.id
)),
);
task.force_hold();
entry = VmEntry::Run;
continue;
}
Ok(exit) => exit,
};
entry = vcpu.process_vmexit(&exit).unwrap_or_else(|| {
match exit.kind {
VmExitKind::Inout(pio) => {
slog::error!(
&log,
"Unhandled pio {:x?}", pio; "rip" => exit.rip
);
VmEntry::InoutFulfill(exits::InoutRes::emulate_failed(
&pio,
))
}
VmExitKind::Mmio(mmio) => {
slog::error!(
&log,
"Unhandled mmio {:x?}", mmio; "rip" => exit.rip
);
VmEntry::MmioFulfill(exits::MmioRes::emulate_failed(
&mmio,
))
}
VmExitKind::Rdmsr(msr) => {
slog::error!(
&log,
"Unhandled rdmsr {:#08x}", msr; "rip" => exit.rip
);
let _ = vcpu.set_reg(
bhyve_api::vm_reg_name::VM_REG_GUEST_RAX,
0,
);
let _ = vcpu.set_reg(
bhyve_api::vm_reg_name::VM_REG_GUEST_RDX,
0,
);
VmEntry::Run
}
VmExitKind::Wrmsr(msr, val) => {
slog::error!(
&log,
"Unhandled wrmsr {:#08x} <- {:#08x}", msr, val;
"rip" => #%exit.rip
);
VmEntry::Run
}
VmExitKind::Suspended(SuspendDetail {
kind,
when: _when,
}) => {
match kind {
exits::Suspend::Halt | exits::Suspend::Reset => {
inner
.eq
.push(kind.into(), EventCtx::Vcpu(vcpu.id));
}
exits::Suspend::TripleFault(vcpuid) => {
if vcpuid == -1 || vcpuid == vcpu.id {
inner.eq.push(
kind.into(),
EventCtx::Vcpu(vcpu.id),
);
}
}
}
task.force_hold();
// The next entry is unimportant as we have queued a
// significant event and halted this vCPU task with the
// expectation that it will be acted upon soon.
VmEntry::Run
}
_ => {
slog::error!(
&log,
"Unhandled exit @rip:{:08x} {:?}",
exit.rip,
exit.kind
);
todo!()
}
}
});
}
}
fn generate_pins(&self) -> (Arc<FuncPin>, Arc<FuncPin>) {
let power_eq = self.0.eq.clone();
let power_pin =
propolis::intr_pins::FuncPin::new(Box::new(move |rising| {
if rising {
power_eq.push(
InstEvent::Halt,
EventCtx::Pin("power pin".to_string()),
);
}
}));
let reset_eq = self.0.eq.clone();
let reset_pin =
propolis::intr_pins::FuncPin::new(Box::new(move |rising| {
if rising {
reset_eq.push(
InstEvent::Reset,
EventCtx::Pin("reset pin".to_string()),
);
}
}));
(Arc::new(power_pin), Arc::new(reset_pin))
}
fn lock(&self) -> Option<MutexGuard<'_, InstState>> {
let guard = self.0.state.lock().unwrap();
// Make sure machine is still "live"
guard.machine.as_ref()?;
Some(guard)
}
fn eq(&self) -> Arc<EventQueue> {
self.0.eq.clone()
}
}
fn build_machine(
name: &str,
max_cpu: u8,
lowmem: usize,
highmem: usize,
use_reservoir: bool,
) -> Result<propolis::Machine> {
let mut builder = Builder::new(
name,
propolis::vmm::CreateOpts {
force: true,
use_reservoir,
..Default::default()
},
)?
.max_cpus(max_cpu)?
.add_mem_region(0, lowmem, "lowmem")?
.add_rom_region(0x1_0000_0000 - MAX_ROM_SIZE, MAX_ROM_SIZE, "bootrom")?
.add_mmio_region(0xc000_0000, 0x2000_0000, "dev32")?
.add_mmio_region(0xe000_0000, 0x1000_0000, "pcicfg")?;
let highmem_start = 0x1_0000_0000;
if highmem > 0 {
builder = builder.add_mem_region(highmem_start, highmem, "highmem")?;
}
let dev64_start = highmem_start + highmem;
builder = builder.add_mmio_region(
dev64_start,
vmm::MAX_PHYSMEM - dev64_start,
"dev64",
)?;
builder.finalize()
}
fn open_bootrom(path: &str) -> Result<(File, usize)> {
let fp = File::open(path)?;
let len = fp.metadata()?.len();
if len & PAGE_OFFSET != 0 {
Err(Error::new(
ErrorKind::InvalidData,
format!(
"rom {} length {:x} not aligned to {:x}",
path,
len,
PAGE_OFFSET + 1
),
))
} else {
Ok((fp, len as usize))
}
}
fn build_log(level: slog::Level) -> slog::Logger {
let main_drain = if atty::is(atty::Stream::Stdout) {
let decorator = slog_term::TermDecorator::new().build();
let drain = slog_term::CompactFormat::new(decorator).build().fuse();
slog_async::Async::new(drain)
.overflow_strategy(slog_async::OverflowStrategy::Block)
.build_no_guard()
} else {
let drain =
slog_bunyan::with_name("propolis-standalone", std::io::stdout())
.build()
.fuse();
slog_async::Async::new(drain)
.overflow_strategy(slog_async::OverflowStrategy::Block)
.build_no_guard()
};
let (dtrace_drain, probe_reg) = slog_dtrace::Dtrace::new();
let filtered_main = slog::LevelFilter::new(main_drain, level);
let log = slog::Logger::root(
slog::Duplicate::new(filtered_main.fuse(), dtrace_drain.fuse()).fuse(),
o!(),
);
if let slog_dtrace::ProbeRegistration::Failed(err) = probe_reg {
slog::error!(&log, "Error registering slog-dtrace probes: {:?}", err);
}
log
}
fn populate_rom(
machine: &Machine,
region_name: &str,
fp: &File,
len: usize,
) -> std::io::Result<()> {
let mem = machine.acc_mem.access().unwrap();
let mapping = mem.direct_writable_region_by_name(region_name)?;
if mapping.len() < len {
return Err(Error::new(ErrorKind::InvalidData, "rom too long"));
}
let offset = mapping.len() - len;
let submapping = mapping.subregion(offset, len).unwrap();
if submapping.pread(fp, len, 0)? != len {
// TODO: Handle short read
return Err(Error::new(ErrorKind::InvalidData, "short read"));
}
Ok(())
}
struct SmbiosParams {
memory_size: usize,
rom_size: usize,
rom_version: String,
num_cpus: u8,
cpuid_ident: Option<CpuidValues>,
cpuid_procname: Option<[CpuidValues; 3]>,
}
fn generate_smbios(params: SmbiosParams) -> anyhow::Result<smbios::TableBytes> {
use smbios::table::{type0, type1, type16, type4};
let bios_version = params
.rom_version
.try_into()
.expect("bootrom version string doesn't contain NUL bytes");
let smb_type0 = smbios::table::Type0 {
vendor: "Oxide".try_into().unwrap(),
bios_version,
bios_release_date: "Bureaucracy 41, 3186 YOLD".try_into().unwrap(),
bios_rom_size: ((params.rom_size / (64 * 1024)) - 1) as u8,
bios_characteristics: type0::BiosCharacteristics::UNSUPPORTED,
bios_ext_characteristics: type0::BiosExtCharacteristics::ACPI
| type0::BiosExtCharacteristics::UEFI
| type0::BiosExtCharacteristics::IS_VM,
..Default::default()
};
let smb_type1 = smbios::table::Type1 {
manufacturer: "Oxide".try_into().unwrap(),
product_name: "OxVM".try_into().unwrap(),
wake_up_type: type1::WakeUpType::PowerSwitch,
..Default::default()
};
let cpuid_vendor = cpuid_utils::host_query(CpuidIdent::leaf(0));
let cpuid_ident = params
.cpuid_ident
.unwrap_or_else(|| cpuid_utils::host_query(CpuidIdent::leaf(1)));
let family = match cpuid_ident.eax & 0xf00 {
// If family ID is 0xf, extended family is added to it
0xf00 => (cpuid_ident.eax >> 20 & 0xff) + 0xf,
// ... otherwise base family ID is used
base => base >> 8,
};
let vendor = CpuidVendor::try_from(cpuid_vendor);
let proc_manufacturer = match vendor {
Ok(CpuidVendor::Intel) => "Intel",
Ok(CpuidVendor::Amd) => "Advanced Micro Devices, Inc.",
_ => "",
}
.try_into()
.unwrap();
let proc_family = match (vendor, family) {
// Zen
(Ok(CpuidVendor::Amd), family) if family >= 0x17 => 0x6b,
//unknown
_ => 0x2,
};
let proc_id = u64::from(cpuid_ident.eax) | u64::from(cpuid_ident.edx) << 32;
let procname_entries = params.cpuid_procname.or_else(|| {
if cpuid_utils::host_query(CpuidIdent::leaf(0x8000_0000)).eax
>= 0x8000_0004
{
Some([
cpuid_utils::host_query(CpuidIdent::leaf(0x8000_0002)),
cpuid_utils::host_query(CpuidIdent::leaf(0x8000_0003)),
cpuid_utils::host_query(CpuidIdent::leaf(0x8000_0004)),
])
} else {
None
}
});
let proc_version = procname_entries
.and_then(|e| cpuid::parse_brand_string(e).ok())
.unwrap_or("".to_string());
let smb_type4 = smbios::table::Type4 {
proc_type: type4::ProcType::Central,
proc_family,
proc_manufacturer,
proc_id,
proc_version: proc_version.as_str().try_into().unwrap_or_default(),
status: type4::ProcStatus::Enabled,
// unknown
proc_upgrade: 0x2,
// make core and thread counts equal for now
core_count: params.num_cpus,
core_enabled: params.num_cpus,
thread_count: params.num_cpus,
proc_characteristics: type4::Characteristics::IS_64_BIT
| type4::Characteristics::MULTI_CORE,
..Default::default()
};
let mut smb_type16 = smbios::table::Type16 {
location: type16::Location::SystemBoard,
array_use: type16::ArrayUse::System,
error_correction: type16::ErrorCorrection::Unknown,
num_mem_devices: 1,
..Default::default()
};
smb_type16.set_max_capacity(params.memory_size);
let phys_mem_array_handle = 0x1600.into();
let mut smb_type17 = smbios::table::Type17 {
phys_mem_array_handle,
// Unknown
form_factor: 0x2,
// Unknown
memory_type: 0x2,
..Default::default()
};
smb_type17.set_size(Some(params.memory_size));
let smb_type32 = smbios::table::Type32::default();
let mut smb_tables = smbios::Tables::new(0x7f00.into());
smb_tables.add(0x0000.into(), &smb_type0).unwrap();
smb_tables.add(0x0100.into(), &smb_type1).unwrap();
smb_tables.add(0x0300.into(), &smb_type4).unwrap();
smb_tables.add(phys_mem_array_handle, &smb_type16).unwrap();
smb_tables.add(0x1700.into(), &smb_type17).unwrap();
smb_tables.add(0x3200.into(), &smb_type32).unwrap();
Ok(smb_tables.commit())
}
fn generate_bootorder(
config: &config::Config,
log: &slog::Logger,
) -> anyhow::Result<Option<fwcfg::Entry>> {
let Some(names) = config.main.boot_order.as_ref() else {
return Ok(None);
};
slog::info!(
log,
"Bootorder declared as {:?}",
config.main.boot_order.as_ref()
);
let mut order = fwcfg::formats::BootOrder::new();
for name in names.iter() {
let dev = config
.devices
.get(name)
.ok_or(anyhow::anyhow!("Could not find device: {name}"))?;
let get_pci_path = || {
dev.options
.get("pci-path")
.and_then(|v| v.as_str())
.and_then(config::parse_bdf)
.expect("PCI device has valid BDF")
};
match dev.driver.as_str() {
"pci-virtio-block" => {
order.add_disk(get_pci_path().location);
}
"pci-nvme" => {
order.add_nvme(get_pci_path().location, 0);
}
driver if driver.starts_with("pci-") => {