1#![no_std]
24#![no_main]
25#![feature(alloc_error_handler)]
26
27extern crate alloc;
28
29use alloc::{string::String, vec::Vec};
37use core::{alloc::Layout, panic::PanicInfo};
38use init_config::{
39 BootPlan, Diagnostic, PlannedKind, PlannedSilo, Policy, Selection, SiloDef,
40 build_plan_with_policy, build_plan_with_reserved, merge_overlay, parse_config,
41};
42use strat9_syscall::{
43 call,
44 data::{
45 SILO_GRANT_ACCESS_WRITE, SILO_GRANT_DMA, SILO_GRANT_IRQ, SILO_GRANT_PATH, SILO_GRANT_PCI,
46 SiloConfig, SiloGrantDesc,
47 },
48};
49mod control;
50pub mod fmt;
51mod launcher;
52mod supervisor;
53use fmt::log_u32;
54
55const EAGAIN: usize = 11;
56const MAX_READ_BYTES: usize = 64 * 1024 * 1024;
57const MAX_READ_EAGAIN: usize = 256;
58
59alloc_freelist::define_freelist_brk_allocator!(
64 pub struct BumpAllocator;
65 brk = strat9_syscall::call::brk;
66 heap_max = 64 * 1024 * 1024;
67);
68
69#[global_allocator]
70static ALLOCATOR: BumpAllocator = BumpAllocator;
71
72#[alloc_error_handler]
73fn alloc_error(_layout: Layout) -> ! {
75 let _ = call::debug_log(b"[init] OOM Fatal\n");
76 call::exit(12);
77}
78
79fn log(msg: &str) {
85 let _ = call::debug_log(msg.as_bytes());
86}
87
88fn log_diagnostic(diagnostic: &Diagnostic) {
90 log("[init] ");
91 log(&diagnostic.message);
92}
93
94fn read_file(path: &str) -> Result<Vec<u8>, &'static str> {
100 let fd = call::openat(0, path, 0x1, 0).map_err(|_| "open failed")?;
101 let mut out = Vec::new();
102
103 let mut chunk = [0u8; 8192]; let mut eagain = 0usize;
106 loop {
107 match call::read(fd as usize, &mut chunk) {
108 Ok(0) => break,
109 Ok(n) => {
110 if out.len() + n > MAX_READ_BYTES {
111 let _ = call::close(fd as usize);
112 log("[init] read_file: file exceeds MAX_READ_BYTES\n");
113 return Err("file too large");
114 }
115 out.extend_from_slice(&chunk[..n]);
116 eagain = 0;
117 }
118 Err(e) if e.to_errno() == EAGAIN => {
119 eagain += 1;
120 if eagain > MAX_READ_EAGAIN {
121 let _ = call::close(fd as usize);
122 return Err("read timeout");
123 }
124 let _ = call::sched_yield();
125 }
126 Err(_) => {
127 let _ = call::close(fd as usize);
128 return Err("read failed");
129 }
130 }
131 }
132 let _ = call::close(fd as usize);
133 Ok(out)
134}
135
136const DEFAULT_SILO_TOML: &str = include_str!("../../../assets/boot/silo.toml");
142
143fn default_silos() -> init_config::ParsedConfig {
145 parse_config(DEFAULT_SILO_TOML)
146}
147
148fn load_primary_silos() -> (Vec<SiloDef>, Vec<Diagnostic>, Policy) {
154 log("[init] load_primary_silos: begin\n");
155 let parsed = match read_file("/initfs/silo.toml") {
156 Ok(data_vec) => match core::str::from_utf8(&data_vec) {
157 Ok(data_str) => {
158 log("[init] load_primary_silos: parse /initfs/silo.toml\n");
159 Some(parse_config(data_str))
160 }
161 Err(_) => {
162 log("[init] Invalid UTF-8 in /initfs/silo.toml, using embedded defaults\n");
163 None
164 }
165 },
166 Err(_) => {
167 log("[init] Missing /initfs/silo.toml, using embedded defaults\n");
168 None
169 }
170 };
171
172 match parsed {
173 Some(parsed) if !parsed.silos.is_empty() => {
174 log("[init] load_primary_silos: parsed file count=");
175 log_u32(parsed.silos.len() as u32);
176 log("\n");
177 (parsed.silos, parsed.diagnostics, parsed.policy)
178 }
179 _ => {
180 log("[init] Empty or unusable /initfs/silo.toml, using embedded defaults\n");
181 let parsed = default_silos();
182 log("[init] load_primary_silos: parsed embedded defaults count=");
183 log_u32(parsed.silos.len() as u32);
184 log("\n");
185 (parsed.silos, parsed.diagnostics, parsed.policy)
186 }
187 }
188}
189
190fn apply_init_target(policy: &mut Policy) {
195 let data = match read_file("/initfs/init.target") {
196 Ok(data) => data,
197 Err(_) => return,
198 };
199 let text = match core::str::from_utf8(&data) {
200 Ok(text) => text,
201 Err(_) => {
202 log("[init] CONFIG ERROR: init.target: invalid UTF-8\n");
203 return;
204 }
205 };
206 let spec = text
207 .lines()
208 .find(|line| !line.trim().is_empty())
209 .unwrap_or("")
210 .trim();
211 match Selection::from_spec(spec) {
212 Ok(selection) => {
213 policy.selection.profile = selection.profile;
214 for name in selection.disabled {
215 if !policy.selection.is_disabled(&name) {
216 policy.selection.disabled.push(name);
217 }
218 }
219 log("[init] target=");
220 log(policy.selection.profile.as_str());
221 log(" disable=");
222 log_u32(policy.selection.disabled.len() as u32);
223 log("\n");
224 }
225 Err(e) => {
226 log("[init] CONFIG ERROR: init.target: ");
227 log(&e);
228 log("\n");
229 }
230 }
231}
232
233fn cmdline_sets_target(cmdline: &str) -> bool {
235 cmdline
236 .split(|c: char| c == '\0' || c.is_whitespace())
237 .any(|token| token.starts_with("init.target="))
238}
239
240fn apply_kernel_cmdline(policy: &mut Policy) {
247 let mut buf = [0u8; 2048];
248 let n = match call::getcmdline(&mut buf) {
249 Ok(n) => n,
250 Err(e) => {
251 log("[init] cmdline: read failed: ");
252 log(e.name());
253 log("\n");
254 return;
255 }
256 };
257 let len = n.min(buf.len());
258 let cmdline = match core::str::from_utf8(&buf[..len]) {
259 Ok(text) => text,
260 Err(_) => {
261 log("[init] cmdline: invalid UTF-8, ignored\n");
262 return;
263 }
264 };
265
266 let selection = Selection::from_kernel_cmdline(cmdline);
267 if !cmdline_sets_target(cmdline) && selection.disabled.is_empty() {
268 return;
269 }
270 if cmdline_sets_target(cmdline) {
271 policy.selection.profile = selection.profile;
272 }
273 for name in selection.disabled {
274 if !policy.selection.is_disabled(&name) {
275 policy.selection.disabled.push(name);
276 }
277 }
278 log("[init] cmdline target=");
279 log(policy.selection.profile.as_str());
280 log(" disable=");
281 log_u32(policy.selection.disabled.len() as u32);
282 log("\n");
283}
284
285pub(crate) fn rebuild_plan(reserved: &[u32]) -> BootPlan {
290 let (mut silos, mut diagnostics, policy) = load_primary_silos();
291 diagnostics.extend(merge_wasm_test_overlay(&mut silos));
292 build_plan_with_reserved(silos, diagnostics, policy, reserved)
293}
294
295fn merge_wasm_test_overlay(silos: &mut Vec<SiloDef>) -> Vec<Diagnostic> {
297 let data = match read_file("/initfs/wasm-test.toml") {
298 Ok(data) => data,
299 Err(_) => return Vec::new(),
300 };
301 let text = match core::str::from_utf8(&data) {
302 Ok(text) => text,
303 Err(_) => {
304 log("[init] Invalid UTF-8 in /initfs/wasm-test.toml, skipping overlay\n");
305 return Vec::new();
306 }
307 };
308 let parsed = parse_config(text);
309 if parsed.silos.is_empty() {
310 return parsed.diagnostics;
311 }
312
313 let added = merge_overlay(silos, parsed.silos);
314 if added > 0 {
315 log("[init] Applied wasm-test overlay silos: ");
316 log_u32(added as u32);
317 log("\n");
318 }
319 parsed.diagnostics
320}
321
322const SILO_FLAG_ADMIN: u64 = 1 << 0;
327const SILO_FLAG_GRAPHICS: u64 = 1 << 1;
328const SILO_FLAG_WEBRTC_NATIVE: u64 = 1 << 2;
329const SILO_FLAG_GRAPHICS_READ_ONLY: u64 = 1 << 3;
330const SILO_FLAG_WEBRTC_TURN_FORCE: u64 = 1 << 4;
331
332fn build_silo_config(silo: &init_config::PlannedSilo) -> SiloConfig {
334 let mut flags = 0u64;
335 if silo.admin {
337 flags |= SILO_FLAG_ADMIN;
338 }
339 if silo.graphics.enabled {
340 flags |= SILO_FLAG_GRAPHICS;
341 if silo.graphics.mode == "webrtc-native" {
342 flags |= SILO_FLAG_WEBRTC_NATIVE;
343 }
344 if silo.graphics.read_only {
345 flags |= SILO_FLAG_GRAPHICS_READ_ONLY;
346 }
347 if silo.graphics.turn_policy == "force" {
348 flags |= SILO_FLAG_WEBRTC_TURN_FORCE;
349 }
350 }
351
352 let mut config = SiloConfig::zero();
353 config.sid = silo.sid;
354 config.mode = silo.mode.0;
355 config.family = silo.family_id;
356 config.flags = flags;
357 config.graphics_max_sessions = if silo.graphics.enabled {
358 if silo.graphics.max_sessions == 0 {
359 1
360 } else {
361 silo.graphics.max_sessions
362 }
363 } else {
364 0
365 };
366 config.graphics_session_ttl_sec = if silo.graphics.enabled {
367 if silo.graphics.session_ttl_sec == 0 {
368 1800
369 } else {
370 silo.graphics.session_ttl_sec
371 }
372 } else {
373 0
374 };
375 config.dma_max_domains = silo.dma.max_domains;
376 config.dma_max_bytes = silo.dma.max_bytes;
377 config.dma_iova_base = silo.dma.iova_base;
378 config.dma_iova_limit = silo.dma.iova_limit;
379 config.dma_fault_policy = silo.dma.fault_policy.to_u8();
380 config
381}
382
383fn wait_for_service(path: &str) -> bool {
389 let mut delay = 10u32;
390 let mut waited = 0u32;
391 loop {
392 if let Ok(handle) = call::ipc_connect(path.as_bytes()) {
393 let _ = call::handle_close(handle);
394 return true;
395 }
396 if waited >= 10_000 {
397 return false;
398 }
399 supervisor::sleep_ms(delay);
400 waited += delay;
401 delay = (delay * 2).min(250);
402 }
403}
404
405pub(crate) struct SiloRuntime {
407 pub name: String,
408 pub sid: u32,
409 pub handle: usize,
410 pub desired: PlannedSilo,
411}
412
413fn boot_silos(
415 plan: BootPlan,
416 supervised: &mut Vec<supervisor::SupervisedChild>,
417 runtimes: &mut Vec<SiloRuntime>,
418) {
419 for s_def in plan.silos {
420 boot_silo(s_def, supervised, runtimes);
421 }
422}
423
424fn grant_descriptors(grants: &[init_config::Grant]) -> (Vec<SiloGrantDesc>, Vec<Vec<u8>>) {
429 let mut descs = Vec::with_capacity(grants.len());
430 let mut buffers: Vec<Vec<u8>> = Vec::new();
431 for grant in grants {
432 let desc = match &grant.kind {
433 init_config::GrantKind::Path { service, write } => {
434 let bytes = service.as_str().as_bytes().to_vec();
435 let desc = SiloGrantDesc {
436 kind: SILO_GRANT_PATH,
437 access: if *write { SILO_GRANT_ACCESS_WRITE } else { 0 },
438 id: bytes.as_ptr() as u64,
439 len: bytes.len() as u64,
440 _reserved: 0,
441 };
442 buffers.push(bytes);
443 desc
444 }
445 init_config::GrantKind::Irq(line) => SiloGrantDesc {
446 kind: SILO_GRANT_IRQ,
447 access: 0,
448 id: *line as u64,
449 len: 0,
450 _reserved: 0,
451 },
452 init_config::GrantKind::Pci(addr) => SiloGrantDesc {
453 kind: SILO_GRANT_PCI,
454 access: 0,
455 id: ((addr.bus as u64) << 16)
456 | ((addr.device as u64) << 8)
457 | (addr.function as u64),
458 len: 0,
459 _reserved: 0,
460 },
461 init_config::GrantKind::Dma(bytes) => SiloGrantDesc {
462 kind: SILO_GRANT_DMA,
463 access: 0,
464 id: *bytes,
465 len: 0,
466 _reserved: 0,
467 },
468 };
469 descs.push(desc);
470 }
471 (descs, buffers)
472}
473
474fn apply_grants(silo_handle: usize, grants: &[init_config::Grant]) -> Result<(), &'static str> {
479 if grants.is_empty() {
480 return Ok(());
481 }
482 let (descs, _buffers) = grant_descriptors(grants);
483 call::silo_grant(silo_handle, &descs).map_err(|e| e.name())?;
485 log("[init] GRANTS: applied ");
486 log_u32(descs.len() as u32);
487 log("\n");
488 if grants
489 .iter()
490 .any(|g| matches!(g.kind, init_config::GrantKind::Irq(_)))
491 {
492 log(
493 "[init] NOTE: irq grants are stored by the kernel but no subsystem consumes them yet\n",
494 );
495 }
496 Ok(())
497}
498
499fn start_strates(
504 silo_handle: usize,
505 s_def: &PlannedSilo,
506 supervised: &mut Vec<supervisor::SupervisedChild>,
507) -> u32 {
508 let mut active_strates = 0u32;
509
510 if s_def.strates.is_empty() {
511 log("[init] No strates declared for silo ");
512 log(&s_def.name);
513 log("\n");
514 }
515
516 for str_def in &s_def.strates {
517 match &str_def.kind {
518 PlannedKind::Elf | PlannedKind::WasmRuntime => {
519 log("[init] -> Strate: ");
520 log(&str_def.name);
521 log("\n");
522 if let Some(launched) = launcher::launch_module(
523 silo_handle,
524 &str_def.name,
525 &str_def.binary,
526 str_def.sha256,
527 ) {
528 supervisor::register(
529 supervised,
530 &str_def.name,
531 launched.pid,
532 silo_handle,
533 launched.module_handle,
534 &s_def.name,
535 s_def.admin,
536 str_def.restart,
537 str_def.critical,
538 str_def.max_restarts,
539 );
540 active_strates += 1;
541 }
542 }
543 PlannedKind::WasmApp { service_label } => {
544 log("[init] -> Wasm-App: ");
545 log(&str_def.name);
546 log("\n");
547 let service_path = alloc::format!("/srv/strate-wasm/{}", service_label);
549 match launcher::run_wasm_app(&service_path, &str_def.binary) {
550 Ok(()) => {
551 log("[init] wasm app started: ");
552 log(&str_def.binary);
553 log("\n");
554 active_strates += 1;
555 }
556 Err(code) => {
557 log("[init] wasm app failed: status=0x");
558 log_u32(code);
559 log(" (service=");
560 log(&service_path);
561 log(", path=");
562 log(&str_def.binary);
563 log(")\n");
564 }
565 }
566 }
567 }
568 }
569
570 active_strates
571}
572
573pub(crate) fn boot_silo(
580 s_def: PlannedSilo,
581 supervised: &mut Vec<supervisor::SupervisedChild>,
582 runtimes: &mut Vec<SiloRuntime>,
583) -> Option<usize> {
584 for path in &s_def.requires {
585 if !wait_for_service(path.as_str()) {
586 log("[init] DEGRADED: silo ");
587 log(&s_def.name);
588 log(" missing required service ");
589 log(path.as_str());
590 log(", skipping\n");
591 return None;
592 }
593 }
594
595 log("[init] Creating Silo: ");
596 log(&s_def.name);
597 log(" (SID=");
598 log_u32(s_def.sid);
599 log(")\n");
600
601 let config = build_silo_config(&s_def);
602
603 let silo_handle = match call::silo_create((&config as *const SiloConfig) as usize) {
604 Ok(h) => h,
605 Err(e) => {
606 log("[init] silo_create failed: ");
607 log(e.name());
608 log("\n");
609 return None;
610 }
611 };
612
613 if let Err(e) = apply_grants(silo_handle, &s_def.grants) {
617 log("[init] silo_grant failed: ");
618 log(&s_def.name);
619 log(" ");
620 log(e);
621 log("\n");
622 if let Err(e) = call::silo_destroy(silo_handle) {
623 log("[init] silo_destroy failed: ");
624 log(e.name());
625 log(", stopping it instead\n");
626 let _ = call::silo_stop(silo_handle);
627 }
628 let _ = call::handle_close(silo_handle);
629 return None;
630 }
631
632 if let Some(ref lbl) = s_def.label {
633 if let Err(e) = call::silo_rename(silo_handle, lbl.as_ptr() as usize, lbl.len()) {
634 log("[init] silo_rename failed: ");
635 log(e.name());
636 log("\n");
637 }
638 }
639
640 let active_strates = start_strates(silo_handle, &s_def, supervised);
641
642 if active_strates == 0 {
646 log("[init] No active strate in silo ");
647 log(&s_def.name);
648 log(", destroying it\n");
649 if let Err(e) = call::silo_destroy(silo_handle) {
650 log("[init] silo_destroy failed: ");
651 log(e.name());
652 log(", stopping it instead\n");
653 let _ = call::silo_stop(silo_handle);
654 }
655 let _ = call::handle_close(silo_handle);
656 return None;
657 }
658
659 runtimes.push(SiloRuntime {
660 name: s_def.name.clone(),
661 sid: s_def.sid,
662 handle: silo_handle,
663 desired: s_def,
664 });
665 Some(silo_handle)
666}
667
668pub(crate) fn reconfigure_silo(
674 handle: usize,
675 s_def: &PlannedSilo,
676 supervised: &mut Vec<supervisor::SupervisedChild>,
677) -> Result<u32, &'static str> {
678 let config = build_silo_config(s_def);
679 call::silo_config(handle, (&config as *const SiloConfig) as usize).map_err(|e| e.name())?;
680 call::silo_grant_reset(handle).map_err(|e| e.name())?;
681 apply_grants(handle, &s_def.grants)?;
682
683 if let Some(ref lbl) = s_def.label {
684 if let Err(e) = call::silo_rename(handle, lbl.as_ptr() as usize, lbl.len()) {
685 log("[init] silo_rename failed: ");
686 log(e.name());
687 log("\n");
688 }
689 }
690
691 Ok(start_strates(handle, s_def, supervised))
692}
693
694#[unsafe(no_mangle)]
695pub unsafe extern "C" fn _start() -> ! {
697 log("[init] Strat9 hierarchical boot starting\n");
698 log("[init] Stage: load primary silos\n");
699 let (mut silos, mut diagnostics, mut policy) = load_primary_silos();
700 log("[init] Stage: apply init.target\n");
701 apply_init_target(&mut policy);
702 log("[init] Stage: apply kernel cmdline\n");
703 apply_kernel_cmdline(&mut policy);
704 log("[init] Stage: merge wasm overlay\n");
705 diagnostics.extend(merge_wasm_test_overlay(&mut silos));
706 log("[init] Stage: ensure required silos\n");
707 let plan = build_plan_with_policy(silos, diagnostics, policy);
708 for diagnostic in &plan.diagnostics {
709 log_diagnostic(diagnostic);
710 }
711 for silo in &plan.silos {
712 if !silo.grants.is_empty() {
713 log("[init] GRANTS: ");
714 log(&silo.name);
715 log(" declares ");
716 log_u32(silo.grants.len() as u32);
717 log(" grant(s)\n");
718 }
719 }
720 log("[init] Stage: boot silos\n");
721 let mut supervised = Vec::with_capacity(supervisor::CAPACITY);
722 let plan_order: Vec<alloc::string::String> =
725 plan.silos.iter().map(|s| s.name.clone()).collect();
726 let mut runtimes = Vec::new();
727 boot_silos(plan, &mut supervised, &mut runtimes);
728 log("[init] Boot complete.\n");
729 let control_port = control::init_port();
730 supervisor::run(supervised, control_port, plan_order, runtimes);
731}
732
733#[panic_handler]
734fn panic(info: &PanicInfo) -> ! {
735 call::handle_panic("init", info)
736}