blob: 652f4943744839493a43c8ff6d001b6c0ff1aaed [file]
// Copyright 2023 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::task::{Kernel, RoleOverrides, Task};
use fidl_fuchsia_scheduler::{
RoleManagerGetProfileForRoleRequest, RoleManagerMarker, RoleManagerSetRoleRequest,
RoleManagerSynchronousProxy, RoleName, RoleTarget, RoleType,
};
use fuchsia_component::client::connect_to_protocol_sync;
use fuchsia_rcu::{RcuBox, RcuReadScope};
use starnix_logging::{impossible_error, log_debug, log_error, log_warn, track_stub};
use starnix_rcu::RcuHashMap;
use starnix_sync::{LockDepMutex, ProfileHandleCacheLock, SystemModeLock};
use starnix_task_command::TaskCommand;
use starnix_uapi::errors::Errno;
use starnix_uapi::{
SCHED_BATCH, SCHED_DEADLINE, SCHED_FIFO, SCHED_IDLE, SCHED_NORMAL, SCHED_RESET_ON_FORK,
SCHED_RR, errno, error, sched_param,
};
use std::sync::Arc;
/// Maximum Linux utilization clamp value (`SCHED_CAPACITY_SCALE`, 1024 = 100% capacity).
pub const SCHED_CAPACITY_SCALE: u32 = 1024;
/// Default system power/scheduling mode active before any mode transition occurs.
pub const DEFAULT_SYSTEM_MODE: &str = "NOMINAL";
/// Bounded timeout for synchronous `fuchsia.scheduler.RoleManager` FIDL calls.
const ROLE_MANAGER_TIMEOUT: zx::MonotonicDuration = zx::MonotonicDuration::from_seconds(5);
/// `zx::Profile` handles for the roles that have been applied so far, keyed by role name.
///
/// Lookups are lock-free, so threads changing roles do not serialize on this cache. Entries are
/// only ever added: a role's profile does not change once `RoleManager` has returned it.
type ProfileHandleCache = RcuHashMap<String, Arc<zx::Profile>, ProfileHandleCacheLock>;
pub struct SchedulerManager {
role_manager: Option<RoleManagerSynchronousProxy>,
role_overrides: RoleOverrides,
profile_handle_cache: ProfileHandleCache,
system_mode: RcuBox<String>,
system_mode_update_lock: LockDepMutex<(), SystemModeLock>,
}
impl Default for SchedulerManager {
fn default() -> Self {
Self {
role_manager: None,
role_overrides: RoleOverrides::default(),
profile_handle_cache: ProfileHandleCache::new(),
system_mode: RcuBox::new(DEFAULT_SYSTEM_MODE.to_string()),
system_mode_update_lock: Default::default(),
}
}
}
impl SchedulerManager {
/// Create a new SchedulerManager which will apply any provided `role_overrides` before
/// computing a role name based on a Task's scheduler state.
pub fn new(role_overrides: RoleOverrides) -> SchedulerManager {
let profile_handle_cache = ProfileHandleCache::new();
let role_manager = fuchsia_runtime::with_thread_self(|thread| {
let role_manager = connect_to_protocol_sync::<RoleManagerMarker>().unwrap();
if let Err(e) = Self::set_zx_thread_role(
&role_manager,
thread,
SchedulerState::default().role_name(),
&profile_handle_cache,
) {
log_debug!("Setting thread role failed ({e:?}), will not set thread priority.");
None
} else {
log_debug!("Thread role set successfully, scheduler manager initialized.");
Some(role_manager)
}
});
SchedulerManager {
role_manager,
role_overrides,
profile_handle_cache,
..Default::default()
}
}
/// Create a new empty SchedulerManager for testing.
pub(crate) fn empty_for_tests() -> Self {
Self::default()
}
/// Create a new SchedulerManager with a custom role manager and overrides for testing.
#[cfg(test)]
pub(crate) fn new_for_tests(
role_manager: Option<RoleManagerSynchronousProxy>,
role_overrides: RoleOverrides,
) -> Self {
Self { role_manager, role_overrides, ..Default::default() }
}
/// Returns the currently active system power mode.
pub fn system_mode(&self) -> String {
self.system_mode.cloned()
}
/// Sets the active system power mode and re-evaluates roles for running tasks whose role
/// overrides depend on the changed system mode.
///
/// Pre-resolves `zx::Profile` handles for all override rules matching `mode` before mutating
/// `self.system_mode`, and rolls back `self.system_mode` and any already-updated tasks if a
/// task fails to sync its role.
// TODO(https://fxbug.dev/576068113): Delegate system_mode transitions to
// fuchsia.scheduler.RoleManager once the 2D profile matrix mode API
// (https://fxbug.dev/323263024) lands.
pub fn set_system_mode(&self, kernel: &Kernel, mode: impl Into<String>) -> Result<(), Errno> {
let new_mode = mode.into();
let _update_guard = self.system_mode_update_lock.lock();
let previous_mode = self.system_mode.cloned();
if previous_mode == new_mode {
return Ok(());
}
let Some(role_manager) = self.role_manager.as_ref() else {
self.system_mode.update(new_mode);
return Ok(());
};
if !self.role_overrides.has_system_mode_transition(&previous_mode, &new_mode) {
self.system_mode.update(new_mode);
return Ok(());
}
for role_name in self.role_overrides.role_names_for_system_mode(&new_mode) {
Self::prewarm_role_profile(role_manager, role_name, &self.profile_handle_cache)?;
}
self.system_mode.update(new_mode);
let tasks: Vec<_> = {
let scope = RcuReadScope::new();
kernel.pids.running_task_ids(&scope).filter_map(|pid| pid.get_task().ok()).collect()
};
for task in &tasks {
if !task.scheduler_state.lock().is_system_mode_dependent {
continue;
}
if let Err(err) = task.sync_scheduler_state_to_role() {
log_warn!(
tid:% = task.tid,
err:?,
previous_mode:%;
"Failed to update thread role on system mode change, rolling back"
);
self.system_mode.update(previous_mode);
let rollback_tasks: Vec<_> = {
let scope = RcuReadScope::new();
kernel
.pids
.running_task_ids(&scope)
.filter_map(|pid| pid.get_task().ok())
.collect()
};
for updated_task in &rollback_tasks {
if !updated_task.scheduler_state.lock().is_system_mode_dependent {
continue;
}
if let Err(rollback_err) = updated_task.sync_scheduler_state_to_role() {
log_error!(
tid:% = updated_task.tid,
rollback_err:?;
"Failed to roll back thread role after system mode transition failure"
);
}
}
return Err(err);
}
}
Ok(())
}
/// Return the currently active role name for this task. Requires read access to `task`'s state,
/// should only be called by code which is not already modifying the provided `task` or holding
/// `task.scheduler_state`.
pub(crate) fn role_name(
&self,
task: &Task,
scheduler_state: &SchedulerState,
) -> Result<&str, Errno> {
let thread_group = task.thread_group();
let thread_group_state = thread_group.read();
// Only inherit custom roles if the process has executed `execve`. Child processes created
// via `fork` only inherit standard scheduling policies (SCHED_NORMAL/SCHED_FIFO) with
// default profiles to maintain basic parity with Linux and prevent demand amplification.
if thread_group_state.did_exec {
let thread_name = task.command();
let process_name = if task.tid == task.pid {
thread_name.clone()
} else {
task.pid.get_task().map_err(|_| errno!(EINVAL))?.command()
};
return Ok(self
.resolve_role_name(
&process_name,
&thread_name,
&task.read().cpuset_path,
task.is_leader(),
scheduler_state,
)
.0);
}
Ok(scheduler_state.role_name())
}
/// Resolves `(role_name, is_system_mode_dependent)` for offline role-override tests without a
/// running `Kernel` or `SchedulerManager` instance.
///
/// Returns an error if `is_leader` is `true` while `process_name != thread_name`, since at
/// runtime in Starnix a thread-group leader (`tid == pid`) always shares a single
/// [`TaskCommand`] for both `process_name` and `thread_name`.
pub fn resolve_role_name_for_tests<'a>(
role_overrides: &'a RoleOverrides,
process_name: &str,
thread_name: &str,
cgroup_path: &str,
is_leader: bool,
scheduler_state: &SchedulerState,
system_mode: &str,
) -> Result<(&'a str, bool), anyhow::Error> {
anyhow::ensure!(
!is_leader || process_name == thread_name,
"is_leader=true requires matching process_name ({process_name:?}) and thread_name ({thread_name:?})"
);
Ok(Self::resolve_role_name_with_overrides(
role_overrides,
&TaskCommand::new(process_name.as_bytes()),
&TaskCommand::new(thread_name.as_bytes()),
cgroup_path,
is_leader,
scheduler_state,
system_mode,
))
}
fn resolve_role_name(
&self,
process_name: &TaskCommand,
thread_name: &TaskCommand,
cgroup_path: &str,
is_leader: bool,
scheduler_state: &SchedulerState,
) -> (&str, bool) {
let scope = RcuReadScope::new();
Self::resolve_role_name_with_overrides(
&self.role_overrides,
process_name,
thread_name,
cgroup_path,
is_leader,
scheduler_state,
self.system_mode.as_ref(&scope),
)
}
fn resolve_role_name_with_overrides<'a>(
role_overrides: &'a RoleOverrides,
process_name: &TaskCommand,
thread_name: &TaskCommand,
cgroup_path: &str,
is_leader: bool,
scheduler_state: &SchedulerState,
system_mode: &str,
) -> (&'a str, bool) {
let (override_name, is_system_mode_dependent) = role_overrides.get_role_name_with_filters(
process_name,
thread_name,
cgroup_path,
is_leader,
scheduler_state.normal_priority().as_nice(),
scheduler_state.uclamp_min,
system_mode,
);
(override_name.unwrap_or_else(|| scheduler_state.role_name()), is_system_mode_dependent)
}
/// Resolves the target scheduler role for `task` and commits the corresponding profile to its
/// Zircon thread if it differs from the previously committed role.
pub(crate) fn commit_thread_role(
&self,
task: &Task,
scheduler_state: &mut SchedulerState,
) -> Result<(), Errno> {
let Some(role_manager) = self.role_manager.as_ref() else {
log_debug!("no role manager for setting role");
return Ok(());
};
let thread_name = task.command();
let process_name = if task.tid == task.pid {
thread_name.clone()
} else {
task.pid
.get_task()
.map(|l| l.command())
.unwrap_or_else(|_| TaskCommand::new(b"<leader exited>"))
};
let (role_name, is_system_mode_dependent) = self.resolve_role_name(
&process_name,
&thread_name,
&task.read().cpuset_path,
task.is_leader(),
scheduler_state,
);
if scheduler_state.committed_role_name.as_deref() == Some(role_name) {
scheduler_state.is_system_mode_dependent = is_system_mode_dependent;
return Ok(());
}
let zircon_thread = {
let running_state = match task.running_state() {
Ok(live) => live,
Err(_) => {
scheduler_state.is_system_mode_dependent = is_system_mode_dependent;
log_debug!(
"thread role update requested for task without live state, skipping"
);
return Ok(());
}
};
let Some(zircon_thread) = running_state.thread.get() else {
scheduler_state.is_system_mode_dependent = is_system_mode_dependent;
log_debug!("thread role update requested for task without thread, skipping");
return Ok(());
};
zircon_thread.clone()
};
Self::set_zx_thread_role(
role_manager,
&zircon_thread.thread,
role_name,
&self.profile_handle_cache,
)?;
scheduler_state.committed_role_name = Some(role_name.to_string());
scheduler_state.is_system_mode_dependent = is_system_mode_dependent;
Ok(())
}
fn set_zx_thread_role(
role_manager: &RoleManagerSynchronousProxy,
thread: &zx::Thread,
role_name: &str,
cache: &ProfileHandleCache,
) -> Result<(), Errno> {
Self::set_zx_thread_role_with_profile_setter(
role_manager,
thread,
role_name,
cache,
|profile| thread.set_profile(profile, 0),
)
}
fn set_zx_thread_role_with_profile_setter(
role_manager: &RoleManagerSynchronousProxy,
thread: &zx::Thread,
role_name: &str,
cache: &ProfileHandleCache,
set_profile: impl FnOnce(&zx::Profile) -> Result<(), zx::Status>,
) -> Result<(), Errno> {
log_debug!(role_name; "setting thread role");
if let Some(profile) = Self::get_cached_profile(cache, role_name) {
return Self::set_zx_thread_profile(role_name, &profile, set_profile);
}
let request = RoleManagerGetProfileForRoleRequest {
role: Some(RoleName { role: role_name.to_string() }),
target: Some(RoleType::Task),
..Default::default()
};
match role_manager
.get_profile_for_role(request, zx::MonotonicInstant::after(ROLE_MANAGER_TIMEOUT))
{
Ok(Ok(response)) => {
let Some(profile) = response.profile else {
log_warn!("GetRole returned success but no profile handle");
return error!(EINVAL);
};
let profile = Self::cache_profile(cache, role_name, profile);
Self::set_zx_thread_profile(role_name, &profile, set_profile)
}
Ok(Err(status)) if status == zx::Status::TIMED_OUT.into_raw() => {
log_warn!(status:%; "GetRole returned TIMED_OUT");
error!(ETIMEDOUT)
}
Ok(Err(e)) => {
log_warn!(e:%; "GetRole returned error");
Self::set_zx_thread_role_legacy(role_manager, thread, role_name)
}
Err(err) if Self::is_fidl_timeout(&err) => {
log_warn!(err:%; "GetRole FIDL call timed out");
error!(ETIMEDOUT)
}
Err(e) => {
log_warn!(e:%; "GetRole FIDL call failed");
Self::set_zx_thread_role_legacy(role_manager, thread, role_name)
}
}
}
fn is_fidl_timeout(err: &fidl::Error) -> bool {
matches!(
err,
fidl::Error::ClientCall(zx::Status::TIMED_OUT)
| fidl::Error::ClientRead(fidl::TransportError::Status(zx::Status::TIMED_OUT))
| fidl::Error::ClientWrite(fidl::TransportError::Status(zx::Status::TIMED_OUT))
)
}
fn map_role_manager_fidl_error(err: &fidl::Error) -> Errno {
if Self::is_fidl_timeout(err) { errno!(ETIMEDOUT) } else { errno!(EINVAL) }
}
fn map_role_manager_status(status: i32) -> Errno {
if status == zx::Status::TIMED_OUT.into_raw() { errno!(ETIMEDOUT) } else { errno!(EINVAL) }
}
/// Returns the cached profile for `role_name`, if any.
fn get_cached_profile(cache: &ProfileHandleCache, role_name: &str) -> Option<Arc<zx::Profile>> {
let scope = RcuReadScope::new();
cache.get(&scope, role_name).cloned()
}
/// Caches `profile` for `role_name`, unless another thread cached one first, and returns the
/// cached profile.
fn cache_profile(
cache: &ProfileHandleCache,
role_name: &str,
profile: zx::Profile,
) -> Arc<zx::Profile> {
cache.lock().entry(role_name.to_string()).or_insert_with(|| Arc::new(profile)).get()
}
/// Applies `profile` to the target thread via `set_profile`.
///
/// Returns:
/// - `Ok(())` if the profile was applied to the thread, or if the thread was in
/// `zx::Status::BAD_STATE` (`INITIAL`, `DYING`, or `DEAD`). For a `zx::Thread`, Zircon only
/// returns `BAD_STATE` due to the thread's lifecycle state; profile parameters are validated
/// when the `zx::Profile` is created.
/// - `Err(EINVAL)` if `profile` is invalid (`BAD_HANDLE`, `WRONG_TYPE`, `ACCESS_DENIED`) or
/// another error occurred.
fn set_zx_thread_profile(
role_name: &str,
profile: &zx::Profile,
set_profile: impl FnOnce(&zx::Profile) -> Result<(), zx::Status>,
) -> Result<(), Errno> {
match set_profile(profile) {
Ok(()) => Ok(()),
// A task's underlying Zircon thread can transition to DYING or DEAD concurrently
// after we snapshot its handle from `task.running_state()`. Ignore `BAD_STATE` just
// as `commit_thread_role` ignores tasks whose live state has already been cleared.
Err(zx::Status::BAD_STATE) => {
log_debug!(
role_name;
"thread role update requested for dead or dying thread, skipping"
);
Ok(())
}
Err(e) => {
log_warn!(role_name, e:%; "Failed to set thread profile from handle");
error!(EINVAL)
}
}
}
/// Pre-resolves and caches the `zx::Profile` handle for `role_name` if not already cached.
///
/// If `RoleManager` returns `ZX_ERR_NOT_SUPPORTED` (indicating a legacy `SetRole`-only test
/// server), returns `Ok(())` so per-task updates can proceed through
/// `set_zx_thread_role_legacy`.
fn prewarm_role_profile(
role_manager: &RoleManagerSynchronousProxy,
role_name: &str,
cache: &ProfileHandleCache,
) -> Result<(), Errno> {
if Self::get_cached_profile(cache, role_name).is_some() {
return Ok(());
}
let request = RoleManagerGetProfileForRoleRequest {
role: Some(RoleName { role: role_name.to_string() }),
target: Some(RoleType::Task),
..Default::default()
};
match role_manager
.get_profile_for_role(request, zx::MonotonicInstant::after(ROLE_MANAGER_TIMEOUT))
{
Ok(Ok(response)) => {
let Some(profile) = response.profile else {
log_warn!(role_name; "GetRole returned success but no profile handle");
return error!(EINVAL);
};
Self::cache_profile(cache, role_name, profile);
Ok(())
}
Ok(Err(status)) if status == zx::Status::NOT_SUPPORTED.into_raw() => Ok(()),
Ok(Err(status)) => {
log_warn!(role_name, status:%; "GetRole returned error during system mode prewarm");
Err(Self::map_role_manager_status(status))
}
Err(err) => {
log_warn!(role_name, err:%; "GetRole FIDL call failed during system mode prewarm");
Err(Self::map_role_manager_fidl_error(&err))
}
}
}
fn set_zx_thread_role_legacy(
role_manager: &RoleManagerSynchronousProxy,
thread: &zx::Thread,
role_name: &str,
) -> Result<(), Errno> {
let thread = thread.duplicate_handle(zx::Rights::SAME_RIGHTS).map_err(impossible_error)?;
let request = RoleManagerSetRoleRequest {
target: Some(RoleTarget::Thread(thread)),
role: Some(RoleName { role: role_name.to_string() }),
..Default::default()
};
match role_manager
.set_role(request, zx::MonotonicInstant::after(ROLE_MANAGER_TIMEOUT))
.map_err(|err| {
log_warn!(err:%; "Unable to set thread role.");
Self::map_role_manager_fidl_error(&err)
})? {
Ok(_) => Ok(()),
// Ignore `BAD_STATE` for dead or dying threads, and ignore `NOT_FOUND` so
// board-specific `RoleOverrides` do not fail `setpriority(2)` or `sched_setattr(2)` on
// emulator configurations where board `.profiles` are not loaded into `RoleManager`.
Err(status)
if status == zx::Status::BAD_STATE.into_raw()
|| status == zx::Status::NOT_FOUND.into_raw() =>
{
log_debug!(
role_name,
status:%;
"SetRole skipped for thread"
);
Ok(())
}
Err(status) => {
log_warn!(status:%; "Unable to set thread role.");
Err(Self::map_role_manager_status(status))
}
}
}
}
/// The task normal priority, used for favoring or disfavoring a task running
/// with some non-real-time scheduling policies. Ranges from -20 to +19 in
/// "user-space" representation and +1 to +40 in "kernel-internal"
/// representation. See "The nice value" at sched(7) for full specification.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub struct NormalPriority {
/// 1 (weakest) to 40 (strongest) (in "kernel-internal" representation),
/// from setpriority()
value: u8,
}
impl NormalPriority {
const MIN_VALUE: u8 = 1;
const DEFAULT_VALUE: u8 = 20;
const MAX_VALUE: u8 = 40;
/// Creates a normal priority from a value to be interpreted according
/// to the "user-space nice" (-20..=19) scale, clamping values outside
/// that scale.
///
/// It would be strange for this to be called from anywhere outside of
/// the setpriority system call.
pub(crate) fn from_setpriority_syscall(user_nice: i32) -> Self {
Self {
value: (Self::DEFAULT_VALUE as i32)
.saturating_sub(user_nice)
.clamp(Self::MIN_VALUE as i32, Self::MAX_VALUE as i32) as u8,
}
}
/// Returns this normal priority's integer representation according
/// to the "user-space nice" (-20..=19) scale.
pub fn as_nice(&self) -> i8 {
(Self::DEFAULT_VALUE as i8) - (self.value as i8)
}
/// Returns this normal priority's integer representation according
/// to the "kernel space nice" (1..=40) scale.
pub(crate) fn raw_priority(&self) -> u8 {
self.value
}
/// Returns whether this normal priority exceeds the given limit.
pub(crate) fn exceeds(&self, limit: u64) -> bool {
limit < (self.value as u64)
}
}
impl std::default::Default for NormalPriority {
fn default() -> Self {
Self { value: Self::DEFAULT_VALUE }
}
}
/// The task real-time priority, used for favoring or disfavoring a task
/// running with real-time scheduling policies. See "Scheduling policies"
/// at sched(7) for full specification.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub(crate) struct RealtimePriority {
/// 1 (weakest) to 99 (strongest), from sched_setscheduler() and
/// sched_setparam(). Only meaningfully used for Fifo and
/// Round-Robin; set to 0 for other policies.
value: u8,
}
impl RealtimePriority {
const NON_REAL_TIME_VALUE: u8 = 0;
const MIN_VALUE: u8 = 1;
const MAX_VALUE: u8 = 99;
const NON_REAL_TIME: RealtimePriority = RealtimePriority { value: Self::NON_REAL_TIME_VALUE };
pub(crate) fn exceeds(&self, limit: u64) -> bool {
limit < (self.value as u64)
}
}
/// The scheduling policies described in "Scheduling policies" at sched(7).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum SchedulingPolicy {
Normal,
Batch,
Idle,
Fifo,
RoundRobin,
}
impl SchedulingPolicy {
fn realtime_priority_min(&self) -> u8 {
match self {
Self::Normal | Self::Batch | Self::Idle => RealtimePriority::NON_REAL_TIME_VALUE,
Self::Fifo | Self::RoundRobin => RealtimePriority::MIN_VALUE,
}
}
fn realtime_priority_max(&self) -> u8 {
match self {
Self::Normal | Self::Batch | Self::Idle => RealtimePriority::NON_REAL_TIME_VALUE,
Self::Fifo | Self::RoundRobin => RealtimePriority::MAX_VALUE,
}
}
pub(crate) fn is_valid_priority(&self, priority: RealtimePriority) -> bool {
(self.realtime_priority_min()..=self.realtime_priority_max()).contains(&priority.value)
}
pub(crate) fn realtime_priority_from(&self, priority: i32) -> Result<RealtimePriority, Errno> {
let priority =
RealtimePriority { value: u8::try_from(priority).map_err(|_| errno!(EINVAL))? };
if !self.is_valid_priority(priority) {
return error!(EINVAL);
}
Ok(priority)
}
}
impl TryFrom<u32> for SchedulingPolicy {
type Error = Errno;
fn try_from(value: u32) -> Result<Self, Errno> {
Ok(match value {
SCHED_NORMAL => Self::Normal,
SCHED_BATCH => Self::Batch,
SCHED_IDLE => Self::Idle,
SCHED_FIFO => Self::Fifo,
SCHED_RR => Self::RoundRobin,
_ => {
return error!(EINVAL);
}
})
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SchedulerState {
pub(crate) policy: SchedulingPolicy,
/// Although nice is only used for Normal and Batch, normal priority
/// ("nice") is still maintained, observable, and alterable when a
/// task is using Idle, Fifo, and RoundRobin.
pub(crate) normal_priority: NormalPriority,
/// 1 (weakest) to 99 (strongest), from sched_setscheduler() and
/// sched_setparam(). Only used for Fifo and Round-Robin.
pub(crate) realtime_priority: RealtimePriority,
pub(crate) reset_on_fork: bool,
/// Per-thread utilization clamp minimum (`0..=1024`), set via `sched_setattr(2)`.
pub(crate) uclamp_min: u32,
/// Per-thread utilization clamp maximum (`0..=1024`), set via `sched_setattr(2)`.
///
/// Note: Starnix and Zircon do not currently support `uclamp_max` clamping when
/// assigning scheduler roles; this value is only stored and reported for
/// `sched_setattr(2)` and `sched_getattr(2)` fidelity.
pub(crate) uclamp_max: u32,
/// The last committed scheduler role name.
committed_role_name: Option<String>,
/// Whether the task's resolved role override depends on the active `system_mode`.
is_system_mode_dependent: bool,
}
impl SchedulerState {
/// Constructs a [`SchedulerState`] from Linux scheduler attributes (`policy`, `nice`,
/// `realtime_priority`, and `uclamp_min`) for role-resolution tests.
pub fn for_tests(
policy: &str,
nice: i32,
realtime_priority: i32,
uclamp_min: u32,
) -> Result<Self, anyhow::Error> {
anyhow::ensure!(
(-20..=19).contains(&nice),
"nice={nice} outside valid Linux range [-20, 19]"
);
anyhow::ensure!(
uclamp_min <= SCHED_CAPACITY_SCALE,
"uclamp_min={uclamp_min} exceeds SCHED_CAPACITY_SCALE ({SCHED_CAPACITY_SCALE})"
);
let raw_policy = match policy {
"SCHED_NORMAL" | "SCHED_OTHER" => SCHED_NORMAL,
"SCHED_BATCH" => SCHED_BATCH,
"SCHED_IDLE" => SCHED_IDLE,
"SCHED_FIFO" => SCHED_FIFO,
"SCHED_RR" => SCHED_RR,
other => anyhow::bail!("unsupported Linux scheduling policy {other:?}"),
};
let policy = SchedulingPolicy::try_from(raw_policy)
.map_err(|e| anyhow::anyhow!("invalid scheduling policy: {e:?}"))?;
let realtime_priority = policy.realtime_priority_from(realtime_priority).map_err(|e| {
anyhow::anyhow!("invalid realtime_priority={realtime_priority} for {policy:?}: {e:?}")
})?;
let normal_priority = NormalPriority::from_setpriority_syscall(nice);
Ok(Self { policy, normal_priority, realtime_priority, uclamp_min, ..Self::default() })
}
pub(crate) fn is_default(&self) -> bool {
let default = Self::default();
self.policy == default.policy
&& self.normal_priority == default.normal_priority
&& self.realtime_priority == default.realtime_priority
&& self.reset_on_fork == default.reset_on_fork
&& self.uclamp_min == default.uclamp_min
&& self.uclamp_max == default.uclamp_max
&& self.committed_role_name.as_deref().is_none_or(|role| role == default.role_name())
}
pub(crate) fn fork(&self) -> Self {
if self.reset_on_fork {
let (policy, normal_priority, realtime_priority) = if self.is_realtime() {
// If the calling task has a real-time scheduling policy, the
// policy given to child processes is SCHED_OTHER and the nice is
// NormalPriority::default() (in all such cases and without caring
// about whether the caller's nice had been stronger or weaker than
// NormalPriority::default()).
(
SchedulingPolicy::Normal,
NormalPriority::default(),
RealtimePriority::NON_REAL_TIME,
)
} else {
// If the calling task has a non-real-time scheduling policy, the
// state given to child processes is the same as that of the
// caller except with the caller's nice clamped to
// NormalPriority::default() at the strongest.
(
self.policy,
std::cmp::min(self.normal_priority, NormalPriority::default()),
RealtimePriority::NON_REAL_TIME,
)
};
// reset_on_fork and utilization clamps revert to their defaults in the child.
Self { policy, normal_priority, realtime_priority, ..Self::default() }
} else {
Self { committed_role_name: None, is_system_mode_dependent: false, ..*self }
}
}
/// Return the policy as an integer (SCHED_NORMAL, SCHED_BATCH, &c) bitwise-ored
/// with the current reset-on-fork status (SCHED_RESET_ON_FORK or 0, depending).
///
/// It would be strange for this to need to be called anywhere outside the
/// implementation of the sched_getscheduler system call.
pub(crate) fn policy_for_sched_getscheduler(&self) -> u32 {
let mut base = match self.policy {
SchedulingPolicy::Normal => SCHED_NORMAL,
SchedulingPolicy::Batch => SCHED_BATCH,
SchedulingPolicy::Idle => SCHED_IDLE,
SchedulingPolicy::Fifo => SCHED_FIFO,
SchedulingPolicy::RoundRobin => SCHED_RR,
};
if self.reset_on_fork {
base |= SCHED_RESET_ON_FORK;
}
base
}
/// Return the priority as a field in a sched_param struct.
///
/// It would be strange for this to need to be called anywhere outside the
/// implementation of the sched_getparam system call.
pub(crate) fn get_sched_param(&self) -> sched_param {
sched_param {
sched_priority: (if self.is_realtime() {
self.realtime_priority.value
} else {
RealtimePriority::NON_REAL_TIME_VALUE
}) as i32,
}
}
pub fn normal_priority(&self) -> NormalPriority {
self.normal_priority
}
/// Returns whether a scheduler role has been committed to the task's Zircon thread.
pub(crate) fn has_committed_role(&self) -> bool {
self.committed_role_name.is_some()
}
/// Returns a monotonic priority key (`0..=139`) for ordering `FUTEX_WAIT` waiters:
/// - `0`: `SCHED_IDLE`
/// - `1..=40`: `SCHED_NORMAL` / `SCHED_BATCH` (`20` is default nice `0`)
/// - `41..=139`: `SCHED_FIFO` / `SCHED_RR` (`40 + realtime_priority`)
pub(crate) fn futex_priority(&self) -> u8 {
match self.policy {
SchedulingPolicy::Idle => 0,
SchedulingPolicy::Normal | SchedulingPolicy::Batch => {
self.normal_priority.raw_priority()
}
SchedulingPolicy::Fifo | SchedulingPolicy::RoundRobin => {
NormalPriority::MAX_VALUE.saturating_add(self.realtime_priority.value)
}
}
}
/// Returns the task priority value as reported in `/proc/<pid>/stat` (see `task_prio` in
/// Linux `kernel/sched/core.c` and `proc_pid_stat(5)`).
///
/// For non-real-time scheduling policies (`SCHED_NORMAL`, `SCHED_BATCH`, `SCHED_IDLE`),
/// this is `20 + nice` in the range `0..=39` (corresponding to nice `-20..=19`).
/// For real-time scheduling policies (`SCHED_FIFO`, `SCHED_RR`), this is
/// `-1 - rt_priority` in the range `-100..=-2` (corresponding to real-time priorities
/// `1..=99`).
pub fn task_priority(&self) -> i64 {
match self.policy {
SchedulingPolicy::Normal | SchedulingPolicy::Batch | SchedulingPolicy::Idle => {
(NormalPriority::DEFAULT_VALUE as i64) + (self.normal_priority.as_nice() as i64)
}
SchedulingPolicy::Fifo | SchedulingPolicy::RoundRobin => {
-1 - (self.realtime_priority.value as i64)
}
}
}
fn is_realtime(&self) -> bool {
match self.policy {
SchedulingPolicy::Normal | SchedulingPolicy::Batch | SchedulingPolicy::Idle => false,
SchedulingPolicy::Fifo | SchedulingPolicy::RoundRobin => true,
}
}
/// Returns a number 0-31 (inclusive) mapping Linux scheduler priority to a Zircon priority
/// level for the fair scheduler.
///
/// The range of 32 Zircon priorities is divided into a region for each flavor of Linux
/// scheduling:
///
/// 1. 0 is used for SCHED_IDLE, the lowest priority Linux tasks.
/// 2. 6-15 (inclusive) is used for lower-than-default-priority SCHED_OTHER/SCHED_BATCH tasks.
/// 3. 16 is used for the default priority SCHED_OTHER/SCHED_BATCH, the same as Zircon's
/// default for Fuchsia processes.
/// 4. 17-26 (inclusive) is used for higher-than-default-priority SCHED_OTHER/SCHED_BATCH tasks.
/// 5. Realtime tasks receive their own profile name.
fn role_name(&self) -> &'static str {
match self.policy {
// Mapped to 0; see "the [...] nice value has no influence for [the SCHED_IDLE] policy"
// at sched(7).
SchedulingPolicy::Idle => FAIR_PRIORITY_ROLE_NAMES[0],
// Configured with nice 0-40 and mapped to 6-26. 20 is the default nice which we want to
// map to 16.
SchedulingPolicy::Normal => {
FAIR_PRIORITY_ROLE_NAMES[(self.normal_priority.value as usize / 2) + 6]
}
SchedulingPolicy::Batch => {
track_stub!(TODO("https://fxbug.dev/308055542"), "SCHED_BATCH hinting");
FAIR_PRIORITY_ROLE_NAMES[(self.normal_priority.value as usize / 2) + 6]
}
// Configured with priority 1-99, mapped to a constant bandwidth profile. Priority
// between realtime tasks is ignored because we don't currently have a way to tell the
// scheduler that a given realtime task is more important than another without
// specifying an earlier deadline for the higher priority task. We can't specify
// deadlines at runtime, so we'll treat their priorities all the same.
SchedulingPolicy::Fifo | SchedulingPolicy::RoundRobin => REALTIME_ROLE_NAME,
}
}
}
impl std::default::Default for SchedulerState {
fn default() -> Self {
Self {
policy: SchedulingPolicy::Normal,
normal_priority: NormalPriority::default(),
realtime_priority: RealtimePriority::NON_REAL_TIME,
reset_on_fork: false,
uclamp_min: 0,
uclamp_max: SCHED_CAPACITY_SCALE,
committed_role_name: None,
is_system_mode_dependent: false,
}
}
}
pub(crate) fn min_priority_for_sched_policy(policy: u32) -> Result<u8, Errno> {
Ok(match policy {
SCHED_DEADLINE => RealtimePriority::NON_REAL_TIME_VALUE,
_ => SchedulingPolicy::try_from(policy)?.realtime_priority_min(),
})
}
pub(crate) fn max_priority_for_sched_policy(policy: u32) -> Result<u8, Errno> {
Ok(match policy {
SCHED_DEADLINE => RealtimePriority::NON_REAL_TIME_VALUE,
_ => SchedulingPolicy::try_from(policy)?.realtime_priority_max(),
})
}
/// Names of RoleManager roles for each static Zircon priority in the fair scheduler.
/// The index in the array is equal to the static priority.
// LINT.IfChange
// Each default role in `starnix.profiles` sets `"affinity": "all"` so reverting from an
// affinity-restricted `RoleOverrides` profile clears the thread's Zircon soft affinity mask.
const FAIR_PRIORITY_ROLE_NAMES: [&str; 32] = [
"fuchsia.starnix.fair.0",
"fuchsia.starnix.fair.1",
"fuchsia.starnix.fair.2",
"fuchsia.starnix.fair.3",
"fuchsia.starnix.fair.4",
"fuchsia.starnix.fair.5",
"fuchsia.starnix.fair.6",
"fuchsia.starnix.fair.7",
"fuchsia.starnix.fair.8",
"fuchsia.starnix.fair.9",
"fuchsia.starnix.fair.10",
"fuchsia.starnix.fair.11",
"fuchsia.starnix.fair.12",
"fuchsia.starnix.fair.13",
"fuchsia.starnix.fair.14",
"fuchsia.starnix.fair.15",
"fuchsia.starnix.fair.16",
"fuchsia.starnix.fair.17",
"fuchsia.starnix.fair.18",
"fuchsia.starnix.fair.19",
"fuchsia.starnix.fair.20",
"fuchsia.starnix.fair.21",
"fuchsia.starnix.fair.22",
"fuchsia.starnix.fair.23",
"fuchsia.starnix.fair.24",
"fuchsia.starnix.fair.25",
"fuchsia.starnix.fair.26",
"fuchsia.starnix.fair.27",
"fuchsia.starnix.fair.28",
"fuchsia.starnix.fair.29",
"fuchsia.starnix.fair.30",
"fuchsia.starnix.fair.31",
];
const REALTIME_ROLE_NAME: &str = "fuchsia.starnix.realtime";
// LINT.ThenChange(//src/starnix/config/starnix.profiles)
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::{spawn_kernel_and_run_sync, spawn_kernel_with_scheduler_and_run_sync};
use fidl_fuchsia_scheduler::{
RoleManagerGetProfileForRoleResponse, RoleManagerRequest, RoleManagerSetRoleResponse,
};
use fuchsia_async::LocalExecutor;
use futures::StreamExt;
use futures::channel::oneshot;
use starnix_sync::Mutex;
use starnix_uapi::signals::SIGCHLD;
use starnix_uapi::{CLONE_SIGHAND, CLONE_THREAD, CLONE_VM};
use std::sync::{Arc, Barrier};
use std::thread;
#[fuchsia::test]
fn default_role_name() {
assert_eq!(SchedulerState::default().role_name(), "fuchsia.starnix.fair.16");
}
#[fuchsia::test]
fn scheduler_state_is_default() {
assert!(SchedulerState::default().is_default());
assert!(
SchedulerState {
committed_role_name: Some("fuchsia.starnix.fair.16".to_string()),
..SchedulerState::default()
}
.is_default()
);
assert!(
SchedulerState {
committed_role_name: Some("fuchsia.starnix.fair.16".to_string()),
is_system_mode_dependent: true,
..SchedulerState::default()
}
.is_default()
);
assert!(
!SchedulerState {
committed_role_name: Some("overridden_role".to_string()),
..SchedulerState::default()
}
.is_default()
);
assert!(
!SchedulerState { policy: SchedulingPolicy::Idle, ..SchedulerState::default() }
.is_default()
);
assert!(
!SchedulerState {
normal_priority: NormalPriority { value: 10 },
..SchedulerState::default()
}
.is_default()
);
assert!(!SchedulerState { reset_on_fork: true, ..SchedulerState::default() }.is_default());
assert!(!SchedulerState { uclamp_min: 128, ..SchedulerState::default() }.is_default());
assert!(!SchedulerState { uclamp_max: 512, ..SchedulerState::default() }.is_default());
}
#[fuchsia::test]
fn scheduler_state_fork_clears_committed_role_name() {
let state = SchedulerState {
policy: SchedulingPolicy::Fifo,
normal_priority: NormalPriority { value: 30 },
realtime_priority: RealtimePriority { value: 50 },
reset_on_fork: false,
uclamp_min: 256,
uclamp_max: 768,
committed_role_name: Some("fuchsia.starnix.realtime".to_string()),
is_system_mode_dependent: true,
};
assert_eq!(
state.fork(),
SchedulerState {
policy: SchedulingPolicy::Fifo,
normal_priority: NormalPriority { value: 30 },
realtime_priority: RealtimePriority { value: 50 },
reset_on_fork: false,
uclamp_min: 256,
uclamp_max: 768,
committed_role_name: None,
is_system_mode_dependent: false,
}
);
let reset_realtime_state = SchedulerState { reset_on_fork: true, ..state };
assert_eq!(
reset_realtime_state.fork(),
SchedulerState {
policy: SchedulingPolicy::Normal,
normal_priority: NormalPriority::default(),
realtime_priority: RealtimePriority::NON_REAL_TIME,
reset_on_fork: false,
uclamp_min: 0,
uclamp_max: SCHED_CAPACITY_SCALE,
committed_role_name: None,
is_system_mode_dependent: false,
}
);
let reset_normal_state = SchedulerState {
policy: SchedulingPolicy::Normal,
normal_priority: NormalPriority { value: 30 },
realtime_priority: RealtimePriority::NON_REAL_TIME,
reset_on_fork: true,
uclamp_min: 512,
uclamp_max: 512,
committed_role_name: Some("fuchsia.starnix.fair.21".to_string()),
is_system_mode_dependent: true,
};
assert_eq!(
reset_normal_state.fork(),
SchedulerState {
policy: SchedulingPolicy::Normal,
normal_priority: NormalPriority::default(),
realtime_priority: RealtimePriority::NON_REAL_TIME,
reset_on_fork: false,
uclamp_min: 0,
uclamp_max: SCHED_CAPACITY_SCALE,
committed_role_name: None,
is_system_mode_dependent: false,
}
);
}
#[fuchsia::test]
fn normal_with_non_default_nice_role_name() {
assert_eq!(
SchedulerState {
policy: SchedulingPolicy::Normal,
normal_priority: NormalPriority { value: 10 },
..SchedulerState::default()
}
.role_name(),
"fuchsia.starnix.fair.11"
);
assert_eq!(
SchedulerState {
policy: SchedulingPolicy::Normal,
normal_priority: NormalPriority { value: 27 },
..SchedulerState::default()
}
.role_name(),
"fuchsia.starnix.fair.19"
);
}
#[fuchsia::test]
fn fifo_role_name() {
assert_eq!(
SchedulerState {
policy: SchedulingPolicy::Fifo,
realtime_priority: RealtimePriority { value: 1 },
..SchedulerState::default()
}
.role_name(),
"fuchsia.starnix.realtime",
);
assert_eq!(
SchedulerState {
policy: SchedulingPolicy::Fifo,
realtime_priority: RealtimePriority { value: 2 },
..SchedulerState::default()
}
.role_name(),
"fuchsia.starnix.realtime",
);
assert_eq!(
SchedulerState {
policy: SchedulingPolicy::Fifo,
realtime_priority: RealtimePriority { value: 99 },
..SchedulerState::default()
}
.role_name(),
"fuchsia.starnix.realtime",
);
}
#[fuchsia::test]
fn idle_role_name() {
assert_eq!(
SchedulerState {
policy: SchedulingPolicy::Idle,
normal_priority: NormalPriority { value: 1 },
..SchedulerState::default()
}
.role_name(),
"fuchsia.starnix.fair.0"
);
assert_eq!(
SchedulerState { policy: SchedulingPolicy::Idle, ..SchedulerState::default() }
.role_name(),
"fuchsia.starnix.fair.0"
);
assert_eq!(
SchedulerState {
policy: SchedulingPolicy::Idle,
normal_priority: NormalPriority { value: 40 },
..SchedulerState::default()
}
.role_name(),
"fuchsia.starnix.fair.0"
);
}
#[fuchsia::test]
async fn role_overrides_non_realtime() {
spawn_kernel_and_run_sync(|current_task| {
let mut builder = RoleOverrides::new();
builder.add("my_task", "my_task", None, "overridden_role");
let overrides = builder.build().unwrap();
let manager = SchedulerManager::new_for_tests(None, overrides);
// Set did_exec = true so custom role overrides are applied.
current_task.thread_group().write().did_exec = true;
current_task.set_command_name(TaskCommand::new(b"my_task"));
let mut state = SchedulerState::default();
state.policy = SchedulingPolicy::Normal;
let role = manager.role_name(current_task, &state).expect("role_name");
assert_eq!(role, "overridden_role");
})
.await;
}
#[fuchsia::test]
async fn set_system_mode_updates_matching_task_roles() {
let committed_roles = Arc::new(Mutex::new(Vec::<String>::new()));
let committed_roles_server = committed_roles.clone();
let (stop_tx, stop_rx) = oneshot::channel::<()>();
let (role_manager, server_end) = fidl::endpoints::create_sync_proxy::<RoleManagerMarker>();
let server_thread = thread::spawn(move || {
let mut executor = LocalExecutor::default();
executor.run_singlethreaded(async move {
let mut stream = server_end.into_stream().take_until(stop_rx);
while let Some(Ok(request)) = stream.next().await {
match request {
RoleManagerRequest::GetProfileForRole { responder, .. } => {
let _ = responder.send(Err(zx::Status::NOT_SUPPORTED.into_raw()));
}
RoleManagerRequest::SetRole { payload, responder } => {
if let Some(role) = payload.role {
committed_roles_server.lock().push(role.role);
}
let _ = responder.send(Ok(RoleManagerSetRoleResponse::default()));
}
_ => panic!("unexpected RoleManagerRequest"),
}
}
});
});
let mut builder = RoleOverrides::new();
builder.add_with_filters(
"app_proc",
"app_proc",
None,
None,
None,
None,
None,
Some("^(LAUNCH|LAUNCH_EXTEND)$".to_string()),
"launch_boost_role",
);
builder.add("app_proc", "app_proc", None, "default_app_role");
builder.add("static_proc", "static_proc", None, "default_app_role");
let overrides = builder.build().unwrap();
let scheduler_manager = SchedulerManager::new_for_tests(Some(role_manager), overrides);
spawn_kernel_with_scheduler_and_run_sync(scheduler_manager, move |current_task| {
current_task.thread_group().write().did_exec = true;
current_task.set_command_name(TaskCommand::new(b"app_proc"));
let kernel = current_task.kernel();
let current_role = || {
let state = current_task.scheduler_state.lock().clone();
kernel.scheduler.role_name(current_task, &state).unwrap()
};
assert_eq!(kernel.scheduler.system_mode(), DEFAULT_SYSTEM_MODE);
assert_eq!(current_role(), "default_app_role");
assert!(current_task.scheduler_state.lock().is_system_mode_dependent);
assert_eq!(
current_task.scheduler_state.lock().committed_role_name.as_deref(),
Some("default_app_role")
);
assert_eq!(committed_roles.lock().last().map(String::as_str), Some("default_app_role"));
let baseline_calls = committed_roles.lock().len();
kernel.scheduler.set_system_mode(kernel, "LAUNCH").expect("set LAUNCH");
assert_eq!(kernel.scheduler.system_mode(), "LAUNCH");
assert_eq!(current_role(), "launch_boost_role");
assert!(current_task.scheduler_state.lock().is_system_mode_dependent);
assert_eq!(
current_task.scheduler_state.lock().committed_role_name.as_deref(),
Some("launch_boost_role")
);
assert_eq!(committed_roles.lock().len(), baseline_calls + 1);
assert_eq!(
committed_roles.lock().last().map(String::as_str),
Some("launch_boost_role")
);
// Transitioning between two modes that match the same rule ("LAUNCH" ->
// "LAUNCH_EXTEND") updates system_mode without re-committing task roles.
kernel.scheduler.set_system_mode(kernel, "LAUNCH_EXTEND").expect("set LAUNCH_EXTEND");
assert_eq!(kernel.scheduler.system_mode(), "LAUNCH_EXTEND");
assert_eq!(
current_task.scheduler_state.lock().committed_role_name.as_deref(),
Some("launch_boost_role")
);
assert_eq!(committed_roles.lock().len(), baseline_calls + 1);
kernel
.scheduler
.set_system_mode(kernel, DEFAULT_SYSTEM_MODE)
.expect("set DEFAULT_SYSTEM_MODE");
assert_eq!(kernel.scheduler.system_mode(), DEFAULT_SYSTEM_MODE);
assert_eq!(
current_task.scheduler_state.lock().committed_role_name.as_deref(),
Some("default_app_role")
);
assert_eq!(committed_roles.lock().len(), baseline_calls + 2);
assert_eq!(committed_roles.lock().last().map(String::as_str), Some("default_app_role"));
// Renaming to a task that only matches an unconditional rule with the same role
// clears `is_system_mode_dependent` even when `committed_role_name` is unchanged,
// so subsequent system_mode transitions skip the task.
current_task.set_command_name(TaskCommand::new(b"static_proc"));
assert!(!current_task.scheduler_state.lock().is_system_mode_dependent);
assert_eq!(
current_task.scheduler_state.lock().committed_role_name.as_deref(),
Some("default_app_role")
);
kernel.scheduler.set_system_mode(kernel, "LAUNCH").expect("set LAUNCH");
assert_eq!(
current_task.scheduler_state.lock().committed_role_name.as_deref(),
Some("default_app_role")
);
assert_eq!(committed_roles.lock().len(), baseline_calls + 2);
kernel
.scheduler
.set_system_mode(kernel, DEFAULT_SYSTEM_MODE)
.expect("set DEFAULT_SYSTEM_MODE");
current_task.set_command_name(TaskCommand::new(b"app_proc"));
assert!(current_task.scheduler_state.lock().is_system_mode_dependent);
// Verify rapid transitions (ending on distinct modes DEFAULT_SYSTEM_MODE vs
// "LAUNCH_EXTEND") are serialized so committed_role_name and the RoleManager server
// always match the winning final system_mode.
let barrier = Barrier::new(3);
let barrier_ref = &barrier;
thread::scope(|scope| {
scope.spawn(move || {
barrier_ref.wait();
for mode in ["LAUNCH", "LAUNCH_EXTEND", DEFAULT_SYSTEM_MODE] {
kernel.scheduler.set_system_mode(kernel, mode).expect("set_system_mode");
}
});
scope.spawn(move || {
barrier_ref.wait();
for mode in [DEFAULT_SYSTEM_MODE, "LAUNCH", "LAUNCH_EXTEND"] {
kernel.scheduler.set_system_mode(kernel, mode).expect("set_system_mode");
}
});
barrier_ref.wait();
});
let final_mode = kernel.scheduler.system_mode();
let expected_role = if final_mode == DEFAULT_SYSTEM_MODE {
"default_app_role"
} else {
"launch_boost_role"
};
assert_eq!(
current_task.scheduler_state.lock().committed_role_name.as_deref(),
Some(expected_role)
);
assert_eq!(committed_roles.lock().last().map(String::as_str), Some(expected_role));
})
.await;
let _ = stop_tx.send(());
server_thread.join().unwrap();
}
#[fuchsia::test]
async fn set_system_mode_prewarm_failure_rejects_without_mutating_mode_or_tasks() {
let get_profile_calls = Arc::new(Mutex::new(Vec::<String>::new()));
let get_profile_calls_server = get_profile_calls.clone();
let set_role_calls = Arc::new(Mutex::new(Vec::<String>::new()));
let set_role_calls_server = set_role_calls.clone();
let (stop_tx, stop_rx) = oneshot::channel::<()>();
let (role_manager, server_end) = fidl::endpoints::create_sync_proxy::<RoleManagerMarker>();
let server_thread = thread::spawn(move || {
let mut executor = LocalExecutor::default();
executor.run_singlethreaded(async move {
let mut stream = server_end.into_stream().take_until(stop_rx);
while let Some(Ok(request)) = stream.next().await {
match request {
RoleManagerRequest::GetProfileForRole { payload, responder } => {
let role = payload.role.as_ref().map(|r| r.role.as_str()).unwrap_or("");
get_profile_calls_server.lock().push(role.to_string());
if role == "missing_launch_role" {
let _ = responder.send(Err(zx::Status::NOT_FOUND.into_raw()));
} else {
let _ = responder.send(Err(zx::Status::NOT_SUPPORTED.into_raw()));
}
}
RoleManagerRequest::SetRole { payload, responder } => {
if let Some(role) = payload.role {
set_role_calls_server.lock().push(role.role);
}
let _ = responder.send(Ok(RoleManagerSetRoleResponse::default()));
}
_ => panic!("unexpected RoleManagerRequest"),
}
}
});
});
let mut builder = RoleOverrides::new();
builder.add_with_filters(
"app_proc",
"app_proc",
None,
None,
None,
None,
None,
Some("^LAUNCH$".to_string()),
"missing_launch_role",
);
builder.add("app_proc", "app_proc", None, "default_app_role");
let overrides = builder.build().unwrap();
let scheduler_manager = SchedulerManager::new_for_tests(Some(role_manager), overrides);
spawn_kernel_with_scheduler_and_run_sync(scheduler_manager, move |current_task| {
current_task.thread_group().write().did_exec = true;
current_task.set_command_name(TaskCommand::new(b"app_proc"));
let kernel = current_task.kernel();
assert_eq!(kernel.scheduler.system_mode(), DEFAULT_SYSTEM_MODE);
assert_eq!(
current_task.scheduler_state.lock().committed_role_name.as_deref(),
Some("default_app_role")
);
get_profile_calls.lock().clear();
let baseline_set_role_calls = set_role_calls.lock().len();
assert_eq!(kernel.scheduler.set_system_mode(kernel, "LAUNCH"), error!(EINVAL));
assert_eq!(kernel.scheduler.system_mode(), DEFAULT_SYSTEM_MODE);
assert_eq!(
current_task.scheduler_state.lock().committed_role_name.as_deref(),
Some("default_app_role")
);
assert_eq!(get_profile_calls.lock().as_slice(), &["missing_launch_role".to_string()]);
assert_eq!(set_role_calls.lock().len(), baseline_set_role_calls);
})
.await;
let _ = stop_tx.send(());
server_thread.join().unwrap();
}
#[fuchsia::test]
fn prewarm_role_profile_caches_handle_and_maps_errors() {
let get_profile_calls = Arc::new(Mutex::new(Vec::<String>::new()));
let get_profile_calls_server = get_profile_calls.clone();
let (stop_tx, stop_rx) = oneshot::channel::<()>();
let (role_manager, server_end) = fidl::endpoints::create_sync_proxy::<RoleManagerMarker>();
let server_thread = thread::spawn(move || {
let mut executor = LocalExecutor::default();
executor.run_singlethreaded(async move {
let mut stream = server_end.into_stream().take_until(stop_rx);
while let Some(Ok(request)) = stream.next().await {
match request {
RoleManagerRequest::GetProfileForRole { payload, responder } => {
let role = payload.role.as_ref().map(|r| r.role.as_str()).unwrap_or("");
get_profile_calls_server.lock().push(role.to_string());
match role {
"legacy_role" => {
let _ =
responder.send(Err(zx::Status::NOT_SUPPORTED.into_raw()));
}
"empty_profile_role" => {
let _ = responder
.send(Ok(RoleManagerGetProfileForRoleResponse::default()));
}
"timed_out_role" => {
let _ = responder.send(Err(zx::Status::TIMED_OUT.into_raw()));
}
_ => {
let _ = responder.send(Err(zx::Status::NOT_FOUND.into_raw()));
}
}
}
_ => panic!("unexpected RoleManagerRequest"),
}
}
});
});
let cache = cache_with_profile_for_test("cached_role");
// Roles already present in `cache` short-circuit without issuing a FIDL RPC.
assert_eq!(
SchedulerManager::prewarm_role_profile(&role_manager, "cached_role", &cache),
Ok(())
);
assert!(get_profile_calls.lock().is_empty());
assert_eq!(
SchedulerManager::prewarm_role_profile(&role_manager, "legacy_role", &cache),
Ok(())
);
assert_eq!(
SchedulerManager::prewarm_role_profile(&role_manager, "empty_profile_role", &cache),
error!(EINVAL)
);
assert_eq!(
SchedulerManager::prewarm_role_profile(&role_manager, "missing_role", &cache),
error!(EINVAL)
);
assert_eq!(
SchedulerManager::prewarm_role_profile(&role_manager, "timed_out_role", &cache),
error!(ETIMEDOUT)
);
assert_eq!(
get_profile_calls.lock().as_slice(),
&[
"legacy_role".to_string(),
"empty_profile_role".to_string(),
"missing_role".to_string(),
"timed_out_role".to_string(),
]
);
let _ = stop_tx.send(());
server_thread.join().unwrap();
}
#[fuchsia::test]
fn prewarm_role_profile_cached_role_does_not_wait_for_cache_lock() {
let (role_manager, server_end) = fidl::endpoints::create_sync_proxy::<RoleManagerMarker>();
// Drop the server endpoint so any fallback FIDL call would fail with PEER_CLOSED.
drop(server_end);
let cache = cache_with_profile_for_test("cached_role");
run_while_holding_cache_lock(&cache, || {
assert_eq!(
SchedulerManager::prewarm_role_profile(&role_manager, "cached_role", &cache),
Ok(())
);
});
}
#[fuchsia::test]
async fn set_system_mode_task_failure_rolls_back_mode_and_updated_tasks() {
let committed_roles = Arc::new(Mutex::new(Vec::<String>::new()));
let committed_roles_server = committed_roles.clone();
let (stop_tx, stop_rx) = oneshot::channel::<()>();
let (role_manager, server_end) = fidl::endpoints::create_sync_proxy::<RoleManagerMarker>();
let server_thread = thread::spawn(move || {
let mut executor = LocalExecutor::default();
executor.run_singlethreaded(async move {
let mut launch_attempts = 0usize;
let mut stream = server_end.into_stream().take_until(stop_rx);
while let Some(Ok(request)) = stream.next().await {
match request {
RoleManagerRequest::GetProfileForRole { responder, .. } => {
let _ = responder.send(Err(zx::Status::NOT_SUPPORTED.into_raw()));
}
RoleManagerRequest::SetRole { payload, responder } => {
let role = payload.role.map(|r| r.role).unwrap_or_default();
if role == "launch_boost_role" {
launch_attempts += 1;
if launch_attempts == 2 {
let _ = responder.send(Err(zx::Status::INTERNAL.into_raw()));
continue;
}
}
committed_roles_server.lock().push(role);
let _ = responder.send(Ok(RoleManagerSetRoleResponse::default()));
}
_ => panic!("unexpected RoleManagerRequest"),
}
}
});
});
let mut builder = RoleOverrides::new();
builder.add_with_filters(
"app_proc",
".*",
None,
None,
None,
None,
None,
Some("^LAUNCH$".to_string()),
"launch_boost_role",
);
builder.add("app_proc", ".*", None, "default_app_role");
let overrides = builder.build().unwrap();
let scheduler_manager = SchedulerManager::new_for_tests(Some(role_manager), overrides);
spawn_kernel_with_scheduler_and_run_sync(scheduler_manager, move |current_task| {
current_task.thread_group().write().did_exec = true;
let sibling = current_task.clone_task_for_test(
(CLONE_THREAD | CLONE_VM | CLONE_SIGHAND) as u64,
Some(SIGCHLD),
);
let leader_thread = current_task.running_state().thread.get().unwrap().clone();
sibling.running_state().thread.set(leader_thread).unwrap();
sibling.set_command_name(TaskCommand::new(b"worker"));
current_task.set_command_name(TaskCommand::new(b"app_proc"));
assert_eq!(
current_task.scheduler_state.lock().committed_role_name.as_deref(),
Some("default_app_role")
);
assert_eq!(
sibling.scheduler_state.lock().committed_role_name.as_deref(),
Some("default_app_role")
);
committed_roles.lock().clear();
let kernel = current_task.kernel();
assert_eq!(kernel.scheduler.set_system_mode(kernel, "LAUNCH"), error!(EINVAL));
assert_eq!(kernel.scheduler.system_mode(), DEFAULT_SYSTEM_MODE);
assert_eq!(
current_task.scheduler_state.lock().committed_role_name.as_deref(),
Some("default_app_role")
);
assert_eq!(
sibling.scheduler_state.lock().committed_role_name.as_deref(),
Some("default_app_role")
);
assert_eq!(
committed_roles.lock().as_slice(),
&["launch_boost_role".to_string(), "default_app_role".to_string()]
);
})
.await;
let _ = stop_tx.send(());
server_thread.join().unwrap();
}
/// Creates a `zx::Profile` wrapping a `zx::Socket` handle.
///
/// Creating a real `zx::Profile` requires the root `ProfileResource`, which is not available in
/// unit tests. When passed to the real `zx::Thread::set_profile` syscall, Zircon rejects this
/// handle with `zx::Status::WRONG_TYPE`, exercising the invalid-profile error path; tests for
/// `Ok(())` and `zx::Status::BAD_STATE` use `set_zx_thread_role_with_profile_setter`.
fn invalid_profile_for_test() -> zx::Profile {
let (client, _server) = zx::Socket::create_stream();
zx::Profile::from(zx::NullableHandle::from(client))
}
fn cache_with_profile_for_test(role_name: &str) -> ProfileHandleCache {
let cache = ProfileHandleCache::new();
cache.insert(role_name.to_string(), Arc::new(invalid_profile_for_test()));
cache
}
/// Runs `f` on another thread while the current thread holds `cache`'s lock.
///
/// If `f` waits for the cache lock, it never returns and the test times out.
fn run_while_holding_cache_lock(cache: &ProfileHandleCache, f: impl FnOnce() + Send) {
let _guard = cache.lock();
thread::scope(|scope| {
scope.spawn(f);
});
}
#[fuchsia::test]
async fn commit_thread_role_failure_does_not_update_committed_role_name() {
spawn_kernel_and_run_sync(|current_task| {
let (role_manager, server_end) =
fidl::endpoints::create_sync_proxy::<RoleManagerMarker>();
drop(server_end);
let manager = SchedulerManager {
role_manager: Some(role_manager),
profile_handle_cache: cache_with_profile_for_test("fuchsia.starnix.fair.16"),
..Default::default()
};
assert_eq!(current_task.scheduler_state.lock().committed_role_name, None);
assert_eq!(
manager.commit_thread_role(current_task, &mut current_task.scheduler_state.lock()),
error!(EINVAL)
);
assert_eq!(current_task.scheduler_state.lock().committed_role_name, None);
current_task.scheduler_state.lock().committed_role_name =
Some("previous_role".to_string());
assert_eq!(
manager.commit_thread_role(current_task, &mut current_task.scheduler_state.lock()),
error!(EINVAL)
);
assert_eq!(
current_task.scheduler_state.lock().committed_role_name.as_deref(),
Some("previous_role")
);
})
.await;
}
#[fuchsia::test]
fn set_zx_thread_role_cached_profile_ok() {
let (role_manager, server_end) = fidl::endpoints::create_sync_proxy::<RoleManagerMarker>();
// Drop the server endpoint so any fallback FIDL call would fail with PEER_CLOSED.
drop(server_end);
let cache = cache_with_profile_for_test("fuchsia.starnix.fair.16");
fuchsia_runtime::with_thread_self(|thread| {
let mut called = false;
let result = SchedulerManager::set_zx_thread_role_with_profile_setter(
&role_manager,
thread,
"fuchsia.starnix.fair.16",
&cache,
|_| {
called = true;
Ok(())
},
);
assert_eq!(result, Ok(()));
assert!(called);
});
}
#[fuchsia::test]
fn set_zx_thread_role_cached_profile_does_not_wait_for_cache_lock() {
let (role_manager, server_end) = fidl::endpoints::create_sync_proxy::<RoleManagerMarker>();
// Drop the server endpoint so any fallback FIDL call would fail with PEER_CLOSED.
drop(server_end);
let cache = cache_with_profile_for_test("fuchsia.starnix.fair.16");
run_while_holding_cache_lock(&cache, || {
fuchsia_runtime::with_thread_self(|thread| {
let mut called = false;
let result = SchedulerManager::set_zx_thread_role_with_profile_setter(
&role_manager,
thread,
"fuchsia.starnix.fair.16",
&cache,
|_| {
called = true;
Ok(())
},
);
assert_eq!(result, Ok(()));
assert!(called);
});
});
}
#[fuchsia::test]
fn set_zx_thread_role_cached_profile_bad_state_is_ignored() {
let (role_manager, server_end) = fidl::endpoints::create_sync_proxy::<RoleManagerMarker>();
// Drop the server endpoint so any fallback FIDL call to RoleManager would fail.
drop(server_end);
let cache = cache_with_profile_for_test("fuchsia.starnix.fair.16");
fuchsia_runtime::with_thread_self(|thread| {
let result = SchedulerManager::set_zx_thread_role_with_profile_setter(
&role_manager,
thread,
"fuchsia.starnix.fair.16",
&cache,
|_| Err(zx::Status::BAD_STATE),
);
assert_eq!(result, Ok(()));
});
}
#[fuchsia::test]
fn set_zx_thread_role_cached_invalid_profile_does_not_call_role_manager() {
let (role_manager, server_end) = fidl::endpoints::create_sync_proxy::<RoleManagerMarker>();
let server_channel = server_end.into_channel();
let watcher = std::thread::spawn(move || {
let signals = server_channel
.wait_one(
zx::Signals::CHANNEL_READABLE | zx::Signals::CHANNEL_PEER_CLOSED,
zx::MonotonicInstant::INFINITE,
)
.to_result()
.expect("wait_one");
signals.contains(zx::Signals::CHANNEL_READABLE)
});
let cache = cache_with_profile_for_test("fuchsia.starnix.fair.16");
fuchsia_runtime::with_thread_self(|thread| {
let result = SchedulerManager::set_zx_thread_role(
&role_manager,
thread,
"fuchsia.starnix.fair.16",
&cache,
);
assert_eq!(result, error!(EINVAL));
});
drop(role_manager);
let received_fidl_request = watcher.join().expect("watcher thread");
assert!(!received_fidl_request);
}
#[fuchsia::test]
fn set_zx_thread_profile_handles_outcomes() {
let profile = invalid_profile_for_test();
assert_eq!(
SchedulerManager::set_zx_thread_profile(
"fuchsia.starnix.fair.16",
&profile,
|_| Ok(())
),
Ok(())
);
assert_eq!(
SchedulerManager::set_zx_thread_profile("fuchsia.starnix.fair.16", &profile, |_| Err(
zx::Status::BAD_STATE
)),
Ok(())
);
assert_eq!(
SchedulerManager::set_zx_thread_profile("fuchsia.starnix.fair.16", &profile, |_| Err(
zx::Status::WRONG_TYPE
)),
error!(EINVAL)
);
}
#[fuchsia::test]
fn set_zx_thread_role_legacy_handles_not_found_and_errors() {
let (stop_tx, stop_rx) = oneshot::channel::<()>();
let (role_manager, server_end) = fidl::endpoints::create_sync_proxy::<RoleManagerMarker>();
let server_thread = thread::spawn(move || {
let mut executor = LocalExecutor::default();
executor.run_singlethreaded(async move {
let mut stream = server_end.into_stream().take_until(stop_rx);
while let Some(Ok(request)) = stream.next().await {
match request {
RoleManagerRequest::SetRole { payload, responder } => {
let role = payload.role.map(|r| r.role).unwrap_or_default();
match role.as_str() {
"missing_board_role" => {
let _ = responder.send(Err(zx::Status::NOT_FOUND.into_raw()));
}
"dead_thread_role" => {
let _ = responder.send(Err(zx::Status::BAD_STATE.into_raw()));
}
"timed_out_role" => {
let _ = responder.send(Err(zx::Status::TIMED_OUT.into_raw()));
}
"internal_err_role" => {
let _ = responder.send(Err(zx::Status::INTERNAL.into_raw()));
}
_ => {
let _ =
responder.send(Ok(RoleManagerSetRoleResponse::default()));
}
}
}
_ => panic!("unexpected RoleManagerRequest"),
}
}
});
});
fuchsia_runtime::with_thread_self(|thread| {
assert_eq!(
SchedulerManager::set_zx_thread_role_legacy(
&role_manager,
thread,
"missing_board_role"
),
Ok(())
);
assert_eq!(
SchedulerManager::set_zx_thread_role_legacy(
&role_manager,
thread,
"dead_thread_role"
),
Ok(())
);
assert_eq!(
SchedulerManager::set_zx_thread_role_legacy(
&role_manager,
thread,
"timed_out_role"
),
error!(ETIMEDOUT)
);
assert_eq!(
SchedulerManager::set_zx_thread_role_legacy(
&role_manager,
thread,
"internal_err_role"
),
error!(EINVAL)
);
});
let _ = stop_tx.send(());
server_thread.join().unwrap();
}
#[fuchsia::test]
fn futex_priority_orders_policies_and_priorities() {
let idle = SchedulerState {
policy: SchedulingPolicy::Idle,
normal_priority: NormalPriority::from_setpriority_syscall(-20),
..SchedulerState::default()
};
let normal_low = SchedulerState {
policy: SchedulingPolicy::Normal,
normal_priority: NormalPriority::from_setpriority_syscall(19),
..SchedulerState::default()
};
let normal_default = SchedulerState::default();
let batch_high = SchedulerState {
policy: SchedulingPolicy::Batch,
normal_priority: NormalPriority::from_setpriority_syscall(-20),
..SchedulerState::default()
};
let fifo_min = SchedulerState {
policy: SchedulingPolicy::Fifo,
realtime_priority: RealtimePriority { value: 1 },
..SchedulerState::default()
};
let rr_max = SchedulerState {
policy: SchedulingPolicy::RoundRobin,
realtime_priority: RealtimePriority { value: 99 },
..SchedulerState::default()
};
assert_eq!(idle.futex_priority(), 0);
assert_eq!(normal_low.futex_priority(), 1);
assert_eq!(normal_default.futex_priority(), 20);
assert_eq!(batch_high.futex_priority(), 40);
assert_eq!(fifo_min.futex_priority(), 41);
assert_eq!(rr_max.futex_priority(), 139);
}
#[fuchsia::test]
fn task_priority_values() {
assert_eq!(SchedulerState::default().task_priority(), 20);
assert_eq!(
SchedulerState {
normal_priority: NormalPriority::from_setpriority_syscall(1),
..SchedulerState::default()
}
.task_priority(),
21
);
assert_eq!(
SchedulerState {
normal_priority: NormalPriority::from_setpriority_syscall(-20),
..SchedulerState::default()
}
.task_priority(),
0
);
assert_eq!(
SchedulerState {
normal_priority: NormalPriority::from_setpriority_syscall(19),
..SchedulerState::default()
}
.task_priority(),
39
);
assert_eq!(
SchedulerState {
policy: SchedulingPolicy::Batch,
normal_priority: NormalPriority::from_setpriority_syscall(-20),
..SchedulerState::default()
}
.task_priority(),
0
);
assert_eq!(
SchedulerState {
policy: SchedulingPolicy::Idle,
normal_priority: NormalPriority::from_setpriority_syscall(-20),
..SchedulerState::default()
}
.task_priority(),
0
);
assert_eq!(
SchedulerState {
policy: SchedulingPolicy::Idle,
normal_priority: NormalPriority::from_setpriority_syscall(5),
..SchedulerState::default()
}
.task_priority(),
25
);
assert_eq!(
SchedulerState {
policy: SchedulingPolicy::Fifo,
realtime_priority: RealtimePriority { value: 1 },
..SchedulerState::default()
}
.task_priority(),
-2
);
assert_eq!(
SchedulerState {
policy: SchedulingPolicy::RoundRobin,
realtime_priority: RealtimePriority { value: 99 },
..SchedulerState::default()
}
.task_priority(),
-100
);
}
#[fuchsia::test]
fn scheduler_state_for_tests_validates_inputs() {
let normal = SchedulerState::for_tests("SCHED_NORMAL", -20, 0, 0).expect("SCHED_NORMAL");
assert_eq!(normal.role_name(), "fuchsia.starnix.fair.26");
let other = SchedulerState::for_tests("SCHED_OTHER", 0, 0, 1024).expect("SCHED_OTHER");
assert_eq!(other.role_name(), "fuchsia.starnix.fair.16");
assert_eq!(other.uclamp_min, 1024);
let batch = SchedulerState::for_tests("SCHED_BATCH", 19, 0, 0).expect("SCHED_BATCH");
assert_eq!(batch.role_name(), "fuchsia.starnix.fair.6");
let idle = SchedulerState::for_tests("SCHED_IDLE", 0, 0, 0).expect("SCHED_IDLE");
assert_eq!(idle.role_name(), "fuchsia.starnix.fair.0");
let fifo = SchedulerState::for_tests("SCHED_FIFO", 0, 1, 0).expect("SCHED_FIFO");
assert_eq!(fifo.role_name(), "fuchsia.starnix.realtime");
let rr = SchedulerState::for_tests("SCHED_RR", 0, 99, 0).expect("SCHED_RR");
assert_eq!(rr.role_name(), "fuchsia.starnix.realtime");
// Out-of-range nice values.
assert!(SchedulerState::for_tests("SCHED_NORMAL", -21, 0, 0).is_err());
assert!(SchedulerState::for_tests("SCHED_NORMAL", 20, 0, 0).is_err());
// Out-of-range uclamp_min (> SCHED_CAPACITY_SCALE).
assert!(SchedulerState::for_tests("SCHED_NORMAL", 0, 0, 1025).is_err());
// Unsupported scheduling policies.
assert!(SchedulerState::for_tests("SCHED_DEADLINE", 0, 0, 0).is_err());
assert!(SchedulerState::for_tests("SCHED_UNKNOWN", 0, 0, 0).is_err());
// Invalid (policy, realtime_priority) pairs.
assert!(SchedulerState::for_tests("SCHED_NORMAL", 0, 1, 0).is_err());
assert!(SchedulerState::for_tests("SCHED_OTHER", 0, -1, 0).is_err());
assert!(SchedulerState::for_tests("SCHED_BATCH", 0, 1, 0).is_err());
assert!(SchedulerState::for_tests("SCHED_IDLE", 0, 1, 0).is_err());
assert!(SchedulerState::for_tests("SCHED_FIFO", 0, 0, 0).is_err());
assert!(SchedulerState::for_tests("SCHED_FIFO", 0, 100, 0).is_err());
assert!(SchedulerState::for_tests("SCHED_RR", 0, 0, 0).is_err());
assert!(SchedulerState::for_tests("SCHED_RR", 0, -1, 0).is_err());
}
#[fuchsia::test]
fn resolve_role_name_for_tests_enforces_leader_name_invariant() {
let mut builder = RoleOverrides::new();
builder.add_with_filters(
"^app$",
"^app$",
None,
Some(true),
None,
None,
None,
None,
"app.leader",
);
let overrides = builder.build().expect("valid regexes");
let state = SchedulerState::for_tests("SCHED_NORMAL", 0, 0, 0).expect("valid state");
assert_eq!(
SchedulerManager::resolve_role_name_for_tests(
&overrides,
"app",
"app",
"/",
true,
&state,
DEFAULT_SYSTEM_MODE,
)
.expect("leader with matching process and thread names"),
("app.leader", false)
);
assert_eq!(
SchedulerManager::resolve_role_name_for_tests(
&overrides,
"app",
"worker",
"/",
false,
&state,
DEFAULT_SYSTEM_MODE,
)
.expect("non-leader with distinct process and thread names"),
("fuchsia.starnix.fair.16", false)
);
let err = SchedulerManager::resolve_role_name_for_tests(
&overrides,
"app",
"main",
"/",
true,
&state,
DEFAULT_SYSTEM_MODE,
)
.expect_err("leader with process != thread must fail");
assert!(
format!("{err:#}").contains("is_leader=true requires matching process_name"),
"{err:#}"
);
}
}