feat(kernel): add a balanced source-kernel choice alongside bin and tuned
Some checks are pending
ci / test (push) Waiting to run

This commit is contained in:
Phoebus 2026-09-29 05:56:34 -07:00
parent aeb46aceee
commit 531b9f0ea5
10 changed files with 504 additions and 83 deletions

View file

@ -5,6 +5,25 @@ this file is the curated, human-readable summary.
## Unreleased — Fast defaults with user-controlled source builds ## Unreleased — Fast defaults with user-controlled source builds
- **Three explicit kernel choices (2026-09-29).** Kernel selection is now a
first-class three-way choice rather than only a prebuilt-vs-source config
enum: `bin` (the default `sys-kernel/gentoo-kernel-bin`, no compile),
`balanced` (source-built `sys-kernel/gentoo-kernel` with the broad
distribution configuration — the fragment makes common hot-plug drivers
explicit as modules: USB Ethernet chipsets, USB mass storage, USB serial, and
removable-media filesystems such as exFAT/NTFS3), and `tuned` (the same broad
coverage plus one conservative optimization; no driver is dropped). New typed
action `BuildBalancedKernel { make_default }` and phrase
`sys build balanced kernel`; both source choices keep `gentoo-kernel-bin`
installed as the known-good fallback and create a separate BLS entry
(`phoebus-balanced.conf` / `phoebus-tuned.conf`) that is only promoted after a
test boot. Core: `fastinstall::{KernelChoice, kernel_build_plan,
balanced_kernel_plan, kernel_build_review}`; `system::{balanced_kernel_config,
tuned_kernel_config}`; executor `kernel::build_balanced_kernel` (refactored
from the tuned path). Gates: `cargo fmt`, `clippy --workspace --all-targets --
-D warnings`, `cargo test --workspace` 849 passed / 0 failed. VM journeys for
the balanced/tuned builds and source conversion are in progress (multi-hour
compiles).
- **OpenCode is now a standard transport (2026-09-29).** The OpenCode backend was - **OpenCode is now a standard transport (2026-09-29).** The OpenCode backend was
special-cased twice: it ran **outside** the model sandbox (a comment called it special-cased twice: it ran **outside** the model sandbox (a comment called it
"a different trust boundary") and its endpoint policy was stricter than the "a different trust boundary") and its endpoint policy was stricter than the

View file

@ -82,6 +82,7 @@ Booting that recovery entry offline remains a manual gate.
| Single generic kernel default (no second generic kernel) | yes | yes (guard + tuned path keeps the fallback) | yes (existing boot path unchanged) | no | | Single generic kernel default (no second generic kernel) | yes | yes (guard + tuned path keeps the fallback) | yes (existing boot path unchanged) | no |
| User-initiated source builds (`convert_to_source`) | yes | yes (table incl. thunderbird, review, build-before-remove, Brave/unknown refusals) | no (no conversion journey run in a VM) | no | | User-initiated source builds (`convert_to_source`) | yes | yes (table incl. thunderbird, review, build-before-remove, Brave/unknown refusals) | no (no conversion journey run in a VM) | no |
| Tuned-kernel build (`build_tuned_kernel`, separate BLS, fallback kept) | yes | yes (refusal without fallback, entry creation, default never blind-switched) | no (no build/boot-test in a VM) | no | | Tuned-kernel build (`build_tuned_kernel`, separate BLS, fallback kept) | yes | yes (refusal without fallback, entry creation, default never blind-switched) | no (no build/boot-test in a VM) | no |
| Balanced source kernel (`build_balanced_kernel`, broad hardware, bin fallback) | yes | yes (plan/fragment/review, refusal without fallback, separate `phoebus-balanced.conf`, default untouched) | in progress (VM build/boot journey started 2026-09-29) | no |
| Installed first-login welcome (once per user, reopenable, non-blocking) | yes | yes (assets, launcher, autostart, QML guards, DMS seed) | no (first login + graphical checks not run) | no | | Installed first-login welcome (once per user, reopenable, non-blocking) | yes | yes (assets, launcher, autostart, QML guards, DMS seed) | no (first login + graphical checks not run) | no |
| Install metrics (time, download, peak disk, installed size) | yes | yes (report rendering; orchestration hooks) | yes (Run 13 recorded 588 compile times into target metrics) | no | | Install metrics (time, download, peak disk, installed size) | yes | yes (report rendering; orchestration hooks) | yes (Run 13 recorded 588 compile times into target metrics) | no |
| XWayland / polkit agent / kitty / wofi | yes | no | installed, not launched | no | | XWayland / polkit agent / kitty / wofi | yes | no | installed, not launched | no |

View file

@ -320,6 +320,16 @@ pub enum SystemAction {
#[serde(default)] #[serde(default)]
make_default: bool, make_default: bool,
}, },
/// Build a **balanced** source kernel (not the prebuilt `-bin`) from the
/// broad distribution configuration, so common hot-pluggable hardware
/// (USB Ethernet, USB storage, extra filesystems) keeps working. Creates a
/// separate BLS entry, boot-tests it before offering to make it default,
/// and always keeps `gentoo-kernel-bin` as the fallback.
BuildBalancedKernel {
/// Make the balanced kernel the default only after a verified boot.
#[serde(default)]
make_default: bool,
},
} }
impl SystemAction { impl SystemAction {
@ -511,6 +521,13 @@ impl SystemAction {
.to_string() .to_string()
} }
} }
SystemAction::BuildBalancedKernel { make_default } => {
if *make_default {
"build a balanced source kernel (broad hardware) and make it default after a verified boot (keeps generic fallback)".to_string()
} else {
"build a balanced source kernel (broad hardware) as a separate boot entry (keeps generic fallback)".to_string()
}
}
} }
} }
@ -570,7 +587,8 @@ impl SystemAction {
| SystemAction::CustomEbuildInstall { .. } | SystemAction::CustomEbuildInstall { .. }
| SystemAction::CustomEbuildRemove { .. } | SystemAction::CustomEbuildRemove { .. }
| SystemAction::ConvertToSource { .. } | SystemAction::ConvertToSource { .. }
| SystemAction::BuildTunedKernel { .. } => Risk::High, | SystemAction::BuildTunedKernel { .. }
| SystemAction::BuildBalancedKernel { .. } => Risk::High,
} }
} }
@ -668,6 +686,7 @@ impl SystemAction {
| SystemAction::CustomEbuildList => Some(Backend::CustomEbuild), | SystemAction::CustomEbuildList => Some(Backend::CustomEbuild),
SystemAction::ConvertToSource { .. } => Some(Backend::PortageSource), SystemAction::ConvertToSource { .. } => Some(Backend::PortageSource),
SystemAction::BuildTunedKernel { .. } => Some(Backend::PortageSource), SystemAction::BuildTunedKernel { .. } => Some(Backend::PortageSource),
SystemAction::BuildBalancedKernel { .. } => Some(Backend::PortageSource),
_ => None, _ => None,
} }
} }
@ -950,6 +969,7 @@ impl SystemAction {
Ok(()) Ok(())
} }
SystemAction::BuildTunedKernel { .. } => Ok(()), SystemAction::BuildTunedKernel { .. } => Ok(()),
SystemAction::BuildBalancedKernel { .. } => Ok(()),
} }
} }
} }
@ -1577,6 +1597,15 @@ fn parse_natural_raw(text: &str) -> Option<SystemAction> {
make_default: false, make_default: false,
}); });
} }
if t == "build balanced kernel"
|| t == "build a balanced kernel"
|| t == "build balanced source kernel"
|| t == "balanced kernel"
{
return Some(SystemAction::BuildBalancedKernel {
make_default: false,
});
}
for prefix in ["build ", "compile "] { for prefix in ["build ", "compile "] {
if let Some(rest) = rest(prefix) { if let Some(rest) = rest(prefix) {
let rest = rest.trim(); let rest = rest.trim();
@ -2292,6 +2321,24 @@ mod tests {
make_default: false make_default: false
}) })
); );
assert_eq!(
parse_natural("build balanced kernel"),
Some(SystemAction::BuildBalancedKernel {
make_default: false
})
);
let balanced_json =
parse_action(r#"{"action":"build_balanced_kernel","make_default":false}"#)
.expect("balanced JSON parses");
assert_eq!(
balanced_json,
SystemAction::BuildBalancedKernel {
make_default: false
}
);
assert_eq!(balanced_json.risk(), Risk::High);
assert!(balanced_json.is_mutating());
assert_eq!(balanced_json.backend(), Some(Backend::PortageSource));
// Brave has no trustworthy source route: the phrase still parses so // Brave has no trustworthy source route: the phrase still parses so
// the refusal carries the reason (resolve_effects fails closed with // the refusal carries the reason (resolve_effects fails closed with
// it before any approval or command). // it before any approval or command).

View file

@ -205,37 +205,149 @@ pub fn source_conversion_review(conv: &SourceConversion) -> String {
o o
} }
/// The opt-in tuned-kernel build plan. /// A user-facing kernel choice. Three options are deliberately distinct:
/// the prebuilt distribution kernel (the default), a source-built **balanced**
/// kernel using the broad distribution configuration (so hot-plugged hardware
/// such as a USB Ethernet adapter or a new filesystem keeps working), and a
/// machine-**tuned** kernel built from the same broad base plus conservative
/// tuning.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KernelChoice {
/// Prebuilt `sys-kernel/gentoo-kernel-bin` (the default; no compile).
Bin,
/// Source-built `sys-kernel/gentoo-kernel` with the broad distribution
/// configuration. Portable and supports common peripherals.
Balanced,
/// Source-built `sys-kernel/gentoo-kernel` plus conservative machine
/// tuning; required drivers are retained.
Tuned,
}
impl KernelChoice {
pub fn as_str(self) -> &'static str {
match self {
KernelChoice::Bin => "bin",
KernelChoice::Balanced => "balanced",
KernelChoice::Tuned => "tuned",
}
}
pub fn label(self) -> &'static str {
match self {
KernelChoice::Bin => "default prebuilt kernel",
KernelChoice::Balanced => "balanced source kernel",
KernelChoice::Tuned => "tuned source kernel",
}
}
pub fn parse(value: &str) -> Option<Self> {
match value.trim().to_ascii_lowercase().as_str() {
"bin" | "prebuilt" | "default" => Some(KernelChoice::Bin),
"balanced" | "broad" | "generic-source" => Some(KernelChoice::Balanced),
"tuned" | "optimized" => Some(KernelChoice::Tuned),
_ => None,
}
}
/// The Portage package this choice installs.
pub fn package(self) -> &'static str {
match self {
KernelChoice::Bin => "sys-kernel/gentoo-kernel-bin",
KernelChoice::Balanced | KernelChoice::Tuned => "sys-kernel/gentoo-kernel",
}
}
/// Every supported choice, in presentation order.
pub fn all() -> [KernelChoice; 3] {
[
KernelChoice::Bin,
KernelChoice::Balanced,
KernelChoice::Tuned,
]
}
}
/// The opt-in source kernel build plan (balanced or tuned).
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct TunedKernelPlan { pub struct KernelBuildPlan {
pub choice: KernelChoice,
pub base_config: &'static str, pub base_config: &'static str,
pub source_atom: &'static str, pub source_atom: &'static str,
pub fallback_atom: &'static str, pub fallback_atom: &'static str,
pub bls_entry: &'static str, pub bls_entry: &'static str,
/// The on-disk config fragment file name under `/etc/kernel/config.d`.
pub fragment_file: &'static str,
} }
pub fn tuned_kernel_plan() -> TunedKernelPlan { /// Kept for existing callers: the tuned plan is the tuned [`KernelBuildPlan`].
TunedKernelPlan { pub type TunedKernelPlan = KernelBuildPlan;
base_config: "Phoebus proven Gentoo distribution-kernel configuration",
source_atom: "sys-kernel/gentoo-kernel", pub fn kernel_build_plan(choice: KernelChoice) -> KernelBuildPlan {
fallback_atom: "sys-kernel/gentoo-kernel-bin", match choice {
bls_entry: "Phoebus (tuned kernel, separate BLS entry)", KernelChoice::Balanced => KernelBuildPlan {
choice,
base_config: "the Gentoo distribution kernel configuration (broad, portable)",
source_atom: "sys-kernel/gentoo-kernel",
fallback_atom: "sys-kernel/gentoo-kernel-bin",
bls_entry: "Phoebus (balanced kernel, separate BLS entry)",
fragment_file: "10-phoebus-balanced.config",
},
// Bin is not a source build; present it plainly if asked.
KernelChoice::Bin => KernelBuildPlan {
choice,
base_config: "the prebuilt Gentoo distribution kernel",
source_atom: "sys-kernel/gentoo-kernel-bin",
fallback_atom: "sys-kernel/gentoo-kernel-bin",
bls_entry: "(the default entry)",
fragment_file: "",
},
KernelChoice::Tuned => KernelBuildPlan {
choice,
base_config: "the proven Gentoo distribution-kernel configuration",
source_atom: "sys-kernel/gentoo-kernel",
fallback_atom: "sys-kernel/gentoo-kernel-bin",
bls_entry: "Phoebus (tuned kernel, separate BLS entry)",
fragment_file: "10-phoebus-tuned.config",
},
} }
} }
/// Review text for the tuned-kernel build. pub fn balanced_kernel_plan() -> KernelBuildPlan {
pub fn tuned_kernel_review(plan: &TunedKernelPlan) -> String { kernel_build_plan(KernelChoice::Balanced)
}
pub fn tuned_kernel_plan() -> KernelBuildPlan {
kernel_build_plan(KernelChoice::Tuned)
}
/// Review text for a source kernel build, describing the specific choice.
pub fn kernel_build_review(plan: &KernelBuildPlan) -> String {
let tuned = plan.choice == KernelChoice::Tuned;
let mut o = String::new(); let mut o = String::new();
o.push_str( o.push_str(&format!(
"Build a kernel tuned for this machine\n========================================\n\n", "Build the {} for this machine\n{}\n\n",
); plan.choice.label(),
"=".repeat(40)
));
o.push_str(&format!(" Start from : {}\n", plan.base_config)); o.push_str(&format!(" Start from : {}\n", plan.base_config));
o.push_str(&format!(" Source package: {}\n", plan.source_atom)); o.push_str(&format!(" Source package: {}\n", plan.source_atom));
o.push_str(" Tuning : only supported, measurable tuning; required storage,\n"); if tuned {
o.push_str(" encryption, filesystem, firmware, input and recovery\n"); o.push_str(
o.push_str(" support are retained.\n"); " Tuning : only supported, measurable tuning; required storage,\n\
o.push_str(" Expected work : typically 20–60 min on 8 vCPUs; ~15 GiB temporary space;\n"); \x20 encryption, filesystem, firmware, input and recovery\n\
o.push_str(" keep AC power connected.\n"); \x20 support are retained.\n",
);
} else {
o.push_str(
" Coverage : the broad distribution configuration is kept, so common\n\
\x20 hot-pluggable hardware (USB Ethernet, USB storage,\n\
\x20 common filesystems) keeps working.\n",
);
}
o.push_str(
" Expected work : typically 20–60 min on 8 vCPUs; ~15 GiB temporary space;\n\
\x20 keep AC power connected.\n",
);
o.push_str(&format!( o.push_str(&format!(
" Boot entry : {} (separate entry; boot-tested first)\n", " Boot entry : {} (separate entry; boot-tested first)\n",
plan.bls_entry plan.bls_entry
@ -244,12 +356,22 @@ pub fn tuned_kernel_review(plan: &TunedKernelPlan) -> String {
" Fallback : {} stays installed and selectable as known-good.\n", " Fallback : {} stays installed and selectable as known-good.\n",
plan.fallback_atom plan.fallback_atom
)); ));
o.push_str(" Safety : a failed build or failed boot never replaces the working\n"); o.push_str(
o.push_str(" default; a clear route back to the generic kernel remains.\n"); " Safety : a failed build or failed boot never replaces the working\n\
o.push_str(" Approval : explicit approval is required before the broker runs.\n"); \x20 default; a clear route back to the generic kernel remains.\n\
\x20Approval : explicit approval is required before the broker runs.\n",
);
o o
} }
pub fn balanced_kernel_review(plan: &KernelBuildPlan) -> String {
kernel_build_review(plan)
}
pub fn tuned_kernel_review(plan: &KernelBuildPlan) -> String {
kernel_build_review(plan)
}
/// Guard: the fast install must not record a permanent preference. /// Guard: the fast install must not record a permanent preference.
/// ///
/// The installer may choose `-bin`/Flatpak/generic-kernel for speed, but it /// The installer may choose `-bin`/Flatpak/generic-kernel for speed, but it
@ -420,6 +542,30 @@ mod tests {
assert!(review.contains("explicit approval")); assert!(review.contains("explicit approval"));
} }
#[test]
fn balanced_kernel_is_broad_and_keeps_the_bin_fallback() {
assert_eq!(KernelChoice::parse("bin"), Some(KernelChoice::Bin));
assert_eq!(
KernelChoice::parse("balanced"),
Some(KernelChoice::Balanced)
);
assert_eq!(KernelChoice::parse("tuned"), Some(KernelChoice::Tuned));
assert_eq!(KernelChoice::all().len(), 3);
assert_eq!(KernelChoice::Bin.package(), "sys-kernel/gentoo-kernel-bin");
assert_eq!(KernelChoice::Balanced.package(), "sys-kernel/gentoo-kernel");
assert_eq!(KernelChoice::Tuned.package(), "sys-kernel/gentoo-kernel");
let plan = balanced_kernel_plan();
assert_eq!(plan.choice, KernelChoice::Balanced);
assert_eq!(plan.source_atom, "sys-kernel/gentoo-kernel");
assert_eq!(plan.fallback_atom, "sys-kernel/gentoo-kernel-bin");
assert_eq!(plan.fragment_file, "10-phoebus-balanced.config");
let review = balanced_kernel_review(&plan);
assert!(review.contains("hot-pluggable hardware"), "{review}");
assert!(review.contains("known-good"), "{review}");
assert!(review.contains("separate entry"), "{review}");
}
#[test] #[test]
fn metrics_report_renders_measurements() { fn metrics_report_renders_measurements() {
let m = InstallMetrics { let m = InstallMetrics {

View file

@ -1231,10 +1231,91 @@ pub fn kernel_profile_config(config: &InstallConfig) -> String {
o o
} }
/// The **balanced** source-kernel fragment: the broad hardware a user may
/// attach later. It is applied on top of the Gentoo distribution-kernel
/// configuration (which is already broad) and makes the common hot-plug
/// drivers explicit as **modules**, so a USB Ethernet adapter, USB storage,
/// serial adapter or a new filesystem keeps working without a rebuild.
///
/// Nothing here disables support; it only ensures presence. `olddefconfig`
/// drops symbols a given kernel version does not know, which is harmless.
pub fn balanced_kernel_config() -> String {
let mut o = String::new();
o.push_str("# Phoebus balanced-kernel fragment (broad hardware coverage).\n");
o.push_str("# Applied on top of the Gentoo distribution-kernel configuration.\n");
o.push_str("# Modules (not built-in) so hot-plugged hardware loads on demand.\n");
o.push_str("\n# USB Ethernet adapters (common chipsets)\n");
for line in [
"CONFIG_USB_USBNET=m",
"CONFIG_USB_NET_AX8817X=m",
"CONFIG_USB_NET_AX88179_178A=m",
"CONFIG_USB_NET_CDCETHER=m",
"CONFIG_USB_NET_CDC_NCM=m",
"CONFIG_USB_NET_CDC_SUBSET=m",
"CONFIG_USB_NET_RNDIS_HOST=m",
"CONFIG_USB_NET_SMSC75XX=m",
"CONFIG_USB_NET_SMSC95XX=m",
"CONFIG_USB_RTL8152=m",
] {
o.push_str(line);
o.push('\n');
}
o.push_str("\n# USB mass storage (flash drives, external disks)\n");
for line in ["CONFIG_USB_STORAGE=m", "CONFIG_USB_UAS=m"] {
o.push_str(line);
o.push('\n');
}
o.push_str("\n# USB serial / embedded debug adapters\n");
for line in [
"CONFIG_USB_ACM=m",
"CONFIG_USB_SERIAL=m",
"CONFIG_USB_SERIAL_FTDI_SIO=m",
"CONFIG_USB_SERIAL_CH341=m",
"CONFIG_USB_SERIAL_CP210X=m",
"CONFIG_USB_SERIAL_PL2303=m",
] {
o.push_str(line);
o.push('\n');
}
o.push_str("\n# Removable-media filesystems (interoperability)\n");
for line in [
"CONFIG_EXFAT_FS=m",
"CONFIG_NTFS3_FS=m",
"CONFIG_VFAT_FS=m",
"CONFIG_MSDOS_FS=m",
"CONFIG_UDF_FS=m",
"CONFIG_F2FS_FS=m",
"CONFIG_XFS_FS=m",
] {
o.push_str(line);
o.push('\n');
}
o.push_str("\n# Thunderbolt / USB4 and firmware loading\n");
for line in ["CONFIG_THUNDERBOLT=m", "CONFIG_FW_LOADER=y"] {
o.push_str(line);
o.push('\n');
}
o
}
/// The **tuned** source-kernel fragment: the broad balanced coverage plus a
/// single supported, measurable optimization. Required drivers are never
/// disabled, so a tuned kernel remains as hardware-tolerant as the balanced one.
pub fn tuned_kernel_config() -> String {
let mut o = balanced_kernel_config();
o.push_str("\n# Tuning (conservative, portable; no -march=native)\n");
o.push_str("CONFIG_CC_OPTIMIZE_FOR_PERFORMANCE=y\n");
o
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Mango + DankMaterialShell (canonical Phoebus desktop) // Mango + DankMaterialShell (canonical Phoebus desktop)
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
/// The Mango session entry point written to `/usr/local/bin/phoebus-session-mango`. /// The Mango session entry point written to `/usr/local/bin/phoebus-session-mango`.
/// ///
/// It starts exactly one compositor (mango), one shell, notification, lock and /// It starts exactly one compositor (mango), one shell, notification, lock and
@ -2352,6 +2433,33 @@ mod tests {
assert!(pkgs.contains(&"net-misc/networkmanager")); assert!(pkgs.contains(&"net-misc/networkmanager"));
} }
#[test]
fn balanced_kernel_config_covers_broad_hardware_and_tuned_adds_only_tuning() {
let balanced = balanced_kernel_config();
// Broad hot-plug coverage: USB Ethernet, USB storage, extra filesystems.
for needle in [
"CONFIG_USB_NET_CDCETHER=m",
"CONFIG_USB_RTL8152=m",
"CONFIG_USB_STORAGE=m",
"CONFIG_EXFAT_FS=m",
"CONFIG_NTFS3_FS=m",
"CONFIG_FW_LOADER=y",
] {
assert!(
balanced.contains(needle),
"balanced missing {needle}: {balanced}"
);
}
assert!(
!balanced.contains("CC_OPTIMIZE_FOR_PERFORMANCE"),
"balanced must not carry tuning"
);
let tuned = tuned_kernel_config();
assert!(tuned.contains("CC_OPTIMIZE_FOR_PERFORMANCE=y"), "{tuned}");
// Tuned retains the broad coverage (drivers are never dropped).
assert!(tuned.contains("CONFIG_USB_NET_CDCETHER=m"), "{tuned}");
}
#[test] #[test]
fn kernel_extras_follow_cpu_features() { fn kernel_extras_follow_cpu_features() {
let cpu = CpuInfo { let cpu = CpuInfo {

View file

@ -74,6 +74,12 @@ pub fn preview(action: &SystemAction) -> String {
&phoebus_core::fastinstall::tuned_kernel_plan(), &phoebus_core::fastinstall::tuned_kernel_plan(),
)); ));
} }
SystemAction::BuildBalancedKernel { .. } => {
out.push('\n');
out.push_str(&phoebus_core::fastinstall::balanced_kernel_review(
&phoebus_core::fastinstall::balanced_kernel_plan(),
));
}
_ => {} _ => {}
} }
out out
@ -219,6 +225,12 @@ fn pretend_args(action: &SystemAction) -> Option<Vec<String>> {
"--".into(), "--".into(),
"sys-kernel/gentoo-kernel".into(), "sys-kernel/gentoo-kernel".into(),
]), ]),
SystemAction::BuildBalancedKernel { .. } => Some(vec![
"--pretend".into(),
"--color=n".into(),
"--".into(),
"sys-kernel/gentoo-kernel".into(),
]),
_ => None, _ => None,
} }
} }
@ -1783,6 +1795,9 @@ pub fn execute_inner(
SystemAction::BuildTunedKernel { make_default } => { SystemAction::BuildTunedKernel { make_default } => {
crate::kernel::build_tuned_kernel(exec, root, *make_default)? crate::kernel::build_tuned_kernel(exec, root, *make_default)?
} }
SystemAction::BuildBalancedKernel { make_default } => {
crate::kernel::build_balanced_kernel(exec, root, *make_default)?
}
}; };
Ok(ActionOutcome { Ok(ActionOutcome {
action: action.clone(), action: action.clone(),

View file

@ -5,6 +5,7 @@
use std::path::Path; use std::path::Path;
use phoebus_core::fastinstall::KernelChoice;
use phoebus_core::policy::{PackagePolicyEngine, PolicyContext}; use phoebus_core::policy::{PackagePolicyEngine, PolicyContext};
use phoebus_core::system as sysgen; use phoebus_core::system as sysgen;
use phoebus_core::{HardwareReport, InstallConfig}; use phoebus_core::{HardwareReport, InstallConfig};
@ -70,56 +71,80 @@ fn assert_only_generic_kernel(packages: &[String]) {
} }
/// Build a kernel tuned for this machine without ever replacing the working /// Build a kernel tuned for this machine without ever replacing the working
/// default. /// default (see [`build_source_kernel`]).
pub fn build_tuned_kernel(exec: &Exec, root: &Path, make_default: bool) -> Result<String> {
build_source_kernel(exec, root, KernelChoice::Tuned, make_default)
}
/// Build a **balanced** source kernel (broad hardware coverage) without ever
/// replacing the working default (see [`build_source_kernel`]).
pub fn build_balanced_kernel(exec: &Exec, root: &Path, make_default: bool) -> Result<String> {
build_source_kernel(exec, root, KernelChoice::Balanced, make_default)
}
/// Build an opt-in source kernel (balanced or tuned) without ever replacing the
/// working default.
/// ///
/// 1. Refuses unless `sys-kernel/gentoo-kernel-bin` is installed (the /// 1. Refuses unless `sys-kernel/gentoo-kernel-bin` is installed (the
/// known-good fallback must exist first). /// known-good fallback must exist first).
/// 2. Writes the tuned fragment on top of the proven distribution-kernel /// 2. Writes the choice's fragment on top of the proven distribution-kernel
/// configuration (supported, measurable tuning only; storage, encryption, /// configuration. The balanced fragment keeps broad hot-plug coverage; the
/// filesystem, firmware, input and recovery support retained). /// tuned fragment adds one conservative optimization and retains it.
/// 3. Builds `sys-kernel/gentoo-kernel` as a binary package first, so a /// 3. Builds `sys-kernel/gentoo-kernel` as a binary package first, so a failed
/// failed build never touches the boot selection. /// build never touches the boot selection.
/// 4. Installs it and creates a **separate** BLS entry. The default is only /// 4. Installs it and creates a **separate** BLS entry. The default is only
/// switched when `make_default` is set **and** the running kernel already /// switched when `make_default` is set **and** the running kernel already is
/// is the tuned one (i.e. after an explicit test boot) — otherwise the /// the source kernel (after an explicit test boot) — otherwise the entry is
/// entry is left for a test boot with the route back documented. /// left for a test boot with the route back documented.
pub fn build_tuned_kernel(exec: &Exec, root: &Path, make_default: bool) -> Result<String> { fn build_source_kernel(
use phoebus_core::fastinstall::tuned_kernel_plan; exec: &Exec,
let plan = tuned_kernel_plan(); root: &Path,
choice: KernelChoice,
make_default: bool,
) -> Result<String> {
use phoebus_core::fastinstall::kernel_build_plan;
let plan = kernel_build_plan(choice);
// 1. The fallback must exist. // 1. The fallback must exist.
if !vdb_has_atom(root, plan.fallback_atom) { if !vdb_has_atom(root, plan.fallback_atom) {
return Err(ExecError::operation( return Err(ExecError::operation(
"sys", "sys",
"build tuned kernel", choice.label(),
format!( format!(
"{} is not installed; refusing to build a tuned kernel without the known-good fallback", "{} is not installed; refusing to build a source kernel without the known-good fallback",
plan.fallback_atom plan.fallback_atom
), ),
)); ));
} }
// 2. Tuned fragment, derived from the proven profile fragment. // 2. The choice's fragment, on top of the proven profile fragment.
let fragment = match choice {
KernelChoice::Balanced => sysgen::balanced_kernel_config(),
KernelChoice::Tuned => sysgen::tuned_kernel_config(),
KernelChoice::Bin => {
return Err(ExecError::operation(
"sys",
choice.label(),
"the prebuilt default kernel is not a source build",
))
}
};
exec.target().write( exec.target().write(
"etc/kernel/config.d/10-phoebus-tuned.config", &format!("etc/kernel/config.d/{}", plan.fragment_file),
tuned_kernel_fragment(), fragment,
)?; )?;
exec.logger.info("wrote tuned kernel fragment"); exec.logger
.info(format!("wrote {} fragment", choice.label()));
// 3. Build only; a failure here leaves boot untouched. // 3. Build only; a failure here leaves boot untouched.
portage::chroot( portage::chroot(
exec, exec,
root, root,
"emerge", "emerge",
&[ &["--ask=n", "--buildpkgonly", "--", plan.source_atom],
"--ask=n",
"--buildpkgonly",
"--",
"sys-kernel/gentoo-kernel",
],
) )
.map_err(|e| { .map_err(|e| {
ExecError::operation( ExecError::operation(
"sys", "sys",
"build tuned kernel", choice.label(),
format!("the tuned kernel build failed; the working default is unchanged: {e}"), format!("the source kernel build failed; the working default is unchanged: {e}"),
) )
})?; })?;
// 4. Install from the verified build, then a separate BLS entry. // 4. Install from the verified build, then a separate BLS entry.
@ -127,26 +152,26 @@ pub fn build_tuned_kernel(exec: &Exec, root: &Path, make_default: bool) -> Resul
exec, exec,
root, root,
"emerge", "emerge",
&["--ask=n", "--usepkg=y", "--", "sys-kernel/gentoo-kernel"], &["--ask=n", "--usepkg=y", "--", plan.source_atom],
) )
.map_err(|e| ExecError::operation("sys", "install tuned kernel", e.to_string()))?; .map_err(|e| ExecError::operation("sys", choice.label(), e.to_string()))?;
if !vdb_has_atom(root, "sys-kernel/gentoo-kernel") { if !vdb_has_atom(root, plan.source_atom) {
return Err(ExecError::operation( return Err(ExecError::operation(
"sys", "sys",
"build tuned kernel", choice.label(),
"the tuned kernel did not verify in the package database; the working default is unchanged", "the source kernel did not verify in the package database; the working default is unchanged",
)); ));
} }
let entry = tuned_bls_entry(root)?; let entry = source_kernel_bls_entry(root, choice)?;
let mut out = format!( let mut out = format!(
"tuned kernel built and verified; separate boot entry `{entry}` created; \ "{} built and verified; separate boot entry `{entry}` created; {} stays the default",
{} stays the default", choice.label(),
plan.fallback_atom plan.fallback_atom
); );
if make_default { if make_default {
if tuned_kernel_is_running(root)? { if tuned_kernel_is_running(root)? {
set_default_entry(exec, root, &entry)?; set_default_entry(exec, root, &entry)?;
out.push_str("; test boot confirmed, tuned kernel is now the default"); out.push_str("; test boot confirmed, the source kernel is now the default");
} else { } else {
out.push_str( out.push_str(
"; not made default yet: boot the new entry once for a test boot, \ "; not made default yet: boot the new entry once for a test boot, \
@ -159,20 +184,6 @@ pub fn build_tuned_kernel(exec: &Exec, root: &Path, make_default: bool) -> Resul
Ok(out) Ok(out)
} }
/// Only supported, measurable tuning on top of the proven base: native
/// optimization markers and build parallelism hints. Required storage,
/// encryption, filesystem, firmware, input and recovery support from the
/// base fragment are retained, never disabled.
fn tuned_kernel_fragment() -> String {
let mut o = String::new();
o.push_str("# Phoebus tuned-kernel fragment (generated).\n");
o.push_str("# Applied on top of the proven Gentoo distribution-kernel\n");
o.push_str("# configuration plus 00-phoebus-profile.config. Only supported,\n");
o.push_str("# measurable tuning; required drivers are never disabled.\n");
o.push_str("CONFIG_CC_OPTIMIZE_FOR_PERFORMANCE=y\n");
o
}
/// Whether a VDB record exists for `atom` under `root`. /// Whether a VDB record exists for `atom` under `root`.
fn vdb_has_atom(root: &Path, atom: &str) -> bool { fn vdb_has_atom(root: &Path, atom: &str) -> bool {
// Normalize versioned/slotted atoms to `category/name` before the lookup. // Normalize versioned/slotted atoms to `category/name` before the lookup.
@ -191,9 +202,10 @@ fn vdb_has_atom(root: &Path, atom: &str) -> bool {
}) })
} }
/// Copy the default BLS entry to a separate tuned-kernel entry. Returns the /// Copy the default BLS entry to a separate source-kernel entry (balanced or
/// new entry file name. Never rewrites the default loader selection. /// tuned). Returns the new entry file name. Never rewrites the default loader
fn tuned_bls_entry(root: &Path) -> Result<String> { /// selection.
fn source_kernel_bls_entry(root: &Path, choice: KernelChoice) -> Result<String> {
let entries = root.join("efi/EFI/Linux"); let entries = root.join("efi/EFI/Linux");
let entries = if entries.is_dir() { let entries = if entries.is_dir() {
entries entries
@ -203,7 +215,7 @@ fn tuned_bls_entry(root: &Path) -> Result<String> {
let Ok(dir) = std::fs::read_dir(&entries) else { let Ok(dir) = std::fs::read_dir(&entries) else {
return Err(ExecError::operation( return Err(ExecError::operation(
"sys", "sys",
"build tuned kernel", choice.label(),
"no BLS entry directory found; refusing to guess the boot layout", "no BLS entry directory found; refusing to guess the boot layout",
)); ));
}; };
@ -216,18 +228,23 @@ fn tuned_bls_entry(root: &Path) -> Result<String> {
let Some(src) = current.first().cloned() else { let Some(src) = current.first().cloned() else {
return Err(ExecError::operation( return Err(ExecError::operation(
"sys", "sys",
"build tuned kernel", choice.label(),
"no existing BLS entry to derive the tuned entry from", "no existing BLS entry to derive the separate entry from",
)); ));
}; };
let text = std::fs::read_to_string(&src).map_err(|e| ExecError::io(src.clone(), e))?; let text = std::fs::read_to_string(&src).map_err(|e| ExecError::io(src.clone(), e))?;
let tuned = format!( let entry = format!(
"{}\n# Phoebus tuned kernel (test entry; generic fallback stays default)\n", "{}\n# Phoebus {} kernel (test entry; generic fallback stays default)\n",
text.trim_end() text.trim_end(),
choice.as_str()
); );
let name = "phoebus-tuned.conf"; let name = match choice {
KernelChoice::Balanced => "phoebus-balanced.conf",
KernelChoice::Tuned => "phoebus-tuned.conf",
KernelChoice::Bin => "phoebus-bin.conf",
};
let dest = entries.join(name); let dest = entries.join(name);
std::fs::write(&dest, tuned).map_err(|e| ExecError::io(dest.clone(), e))?; std::fs::write(&dest, entry).map_err(|e| ExecError::io(dest.clone(), e))?;
Ok(name.to_string()) Ok(name.to_string())
} }
@ -372,4 +389,60 @@ mod tests {
// default install list is exactly the single bin package. // default install list is exactly the single bin package.
assert_only_generic_kernel(&["sys-kernel/gentoo-kernel-bin".to_string()]); assert_only_generic_kernel(&["sys-kernel/gentoo-kernel-bin".to_string()]);
} }
#[test]
fn balanced_build_refuses_without_the_known_good_fallback() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
let err = build_balanced_kernel(&exec, Path::new(&exec.root), false).unwrap_err();
assert!(err.to_string().contains("known-good fallback"), "{err}");
assert!(runner.recorded().is_empty());
}
#[test]
fn balanced_build_creates_a_separate_entry_and_keeps_the_default() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
let root = Path::new(&exec.root);
for dir in [
"var/db/pkg/sys-kernel/gentoo-kernel-bin-6.12.32",
"var/db/pkg/sys-kernel/gentoo-kernel-6.12.32",
] {
std::fs::create_dir_all(root.join(dir)).unwrap();
}
std::fs::create_dir_all(root.join("efi/EFI/Linux")).unwrap();
std::fs::write(
root.join("efi/EFI/Linux/phoebus.conf"),
"title Phoebus\nlinux /vmlinuz-6.12.32\noptions root=/dev/mapper/cryptroot\n",
)
.unwrap();
std::fs::create_dir_all(root.join("efi/loader")).unwrap();
std::fs::write(
root.join("efi/loader/loader.conf"),
"default phoebus.conf\n",
)
.unwrap();
let out = build_balanced_kernel(&exec, root, false).unwrap();
assert!(out.contains("balanced source kernel"), "{out}");
let entry =
std::fs::read_to_string(root.join("efi/EFI/Linux/phoebus-balanced.conf")).unwrap();
assert!(entry.contains("linux /vmlinuz-6.12.32"), "{entry}");
assert!(entry.contains("balanced"), "{entry}");
// The balanced fragment carries broad hot-plug coverage, not tuning.
let frag =
std::fs::read_to_string(root.join("etc/kernel/config.d/10-phoebus-balanced.config"))
.unwrap();
assert!(frag.contains("CONFIG_USB_NET_CDCETHER=m"), "{frag}");
assert!(frag.contains("CONFIG_USB_RTL8152=m"), "{frag}");
assert!(frag.contains("CONFIG_EXFAT_FS=m"), "{frag}");
assert!(
!frag.contains("CC_OPTIMIZE_FOR_PERFORMANCE"),
"balanced must not carry the tuned optimization: {frag}"
);
// The default is untouched.
let loader = std::fs::read_to_string(root.join("efi/loader/loader.conf")).unwrap();
assert!(loader.contains("default phoebus.conf"), "{loader}");
assert!(!loader.contains("phoebus-balanced"), "{loader}");
}
} }

View file

@ -366,6 +366,7 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
sys undo --legacy | sys enable <service> --legacy | \ sys undo --legacy | sys enable <service> --legacy | \
sys choose <app> --legacy | \ sys choose <app> --legacy | \
sys build <app> from source --legacy | \ sys build <app> from source --legacy | \
sys build balanced kernel --legacy | \
sys build tuned kernel --legacy" sys build tuned kernel --legacy"
); );
Err("unsupported instruction in legacy mode".into()) Err("unsupported instruction in legacy mode".into())

View file

@ -900,4 +900,14 @@ fn source_build_and_tuned_kernel_require_root_like_other_mutations() {
assert!(!out.status.success()); assert!(!out.status.success());
let stderr = String::from_utf8_lossy(&out.stderr); let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains("require root"), "stderr: {stderr}"); assert!(stderr.contains("require root"), "stderr: {stderr}");
let out = sys()
.arg("--root")
.arg(root.path())
.args(["build", "balanced", "kernel", "--legacy"])
.output()
.expect("run sys");
assert!(!out.status.success());
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains("require root"), "stderr: {stderr}");
} }

View file

@ -224,6 +224,7 @@ if [[ "$(id -u)" -ne 0 ]]; then
run_expect_nonzero nonroot-clean-cache "require root" clean cache --legacy run_expect_nonzero nonroot-clean-cache "require root" clean cache --legacy
run_expect_nonzero nonroot-source-build "require root" --legacy --action '{"action":"convert_to_source","app":"firefox"}' run_expect_nonzero nonroot-source-build "require root" --legacy --action '{"action":"convert_to_source","app":"firefox"}'
run_expect_nonzero nonroot-tuned-kernel "require root" --legacy build tuned kernel run_expect_nonzero nonroot-tuned-kernel "require root" --legacy build tuned kernel
run_expect_nonzero nonroot-balanced-kernel "require root" --legacy build balanced kernel
fi fi
# User-initiated source builds fail closed before any mutation, even as root: # User-initiated source builds fail closed before any mutation, even as root: