starnix_core/task/
kernel.rs

1// Copyright 2021 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::bpf::EbpfState;
6use crate::device::remote_block_device::RemoteBlockDeviceRegistry;
7use crate::device::{DeviceMode, DeviceRegistry};
8use crate::execution::CrashReporter;
9use crate::mm::{FutexTable, MappingSummary, MlockPinFlavor, SharedFutexKey};
10use crate::power::SuspendResumeManagerHandle;
11use crate::ptrace::StopState;
12use crate::security::{self, AuditLogger};
13use crate::task::container_namespace::ContainerNamespace;
14use crate::task::limits::SystemLimits;
15use crate::task::memory_attribution::MemoryAttributionManager;
16use crate::task::net::NetstackDevices;
17use crate::task::tracing::PidToKoidMap;
18use crate::task::{
19    AbstractUnixSocketNamespace, AbstractVsockSocketNamespace, CurrentTask, DelayedReleaser,
20    IpTables, KernelCgroups, KernelStats, KernelThreads, PidTable, SchedulerManager, Syslog,
21    ThreadGroup, UtsNamespace, UtsNamespaceHandle,
22};
23use crate::time::{HrTimerManager, HrTimerManagerHandle};
24use crate::vdso::vdso_loader::Vdso;
25use crate::vfs::fs_args::MountParams;
26use crate::vfs::socket::{
27    GenericMessage, GenericNetlink, NetlinkAccessControl, NetlinkContextImpl,
28    NetlinkToClientSender, SocketAddress, SocketTokensStore,
29};
30use crate::vfs::{CacheConfig, FileOps, FsNodeHandle, FsString, Mounts, NamespaceNode};
31use bstr::{BString, ByteSlice};
32use devicetree::types::Devicetree;
33use expando::Expando;
34use fidl::endpoints::{
35    ClientEnd, ControlHandle, DiscoverableProtocolMarker, ProtocolMarker, create_endpoints,
36};
37use fidl_fuchsia_component_runner::{ComponentControllerControlHandle, ComponentStopInfo};
38use fidl_fuchsia_feedback::CrashReporterProxy;
39use fidl_fuchsia_time_external::AdjustSynchronousProxy;
40use fuchsia_inspect::ArrayProperty;
41use futures::FutureExt;
42use netlink::interfaces::InterfacesHandler;
43use netlink::{NETLINK_LOG_TAG, Netlink};
44use once_cell::sync::OnceCell;
45use starnix_lifecycle::{AtomicU32Counter, AtomicU64Counter};
46use starnix_logging::{log_debug, log_error, log_info, log_warn};
47use starnix_sync::{
48    FileOpsCore, KernelSwapFiles, LockEqualOrBefore, Locked, Mutex, OrderedMutex, RwLock,
49};
50use starnix_types::ownership::TempRef;
51use starnix_uapi::device_type::DeviceType;
52use starnix_uapi::errors::{Errno, errno};
53use starnix_uapi::open_flags::OpenFlags;
54use starnix_uapi::{VMADDR_CID_HOST, from_status_like_fdio};
55use std::borrow::Cow;
56use std::collections::{HashMap, HashSet};
57use std::num::NonZeroU64;
58use std::path::PathBuf;
59use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU16, Ordering};
60use std::sync::{Arc, OnceLock, Weak};
61use zx::CpuFeatureFlags;
62use {
63    fidl_fuchsia_io as fio, fidl_fuchsia_memory_attribution as fattribution,
64    fuchsia_async as fasync,
65};
66
67#[derive(Debug, Default, Clone)]
68pub struct KernelFeatures {
69    pub bpf_v2: bool,
70
71    /// Whether the kernel supports the S_ISUID and S_ISGID bits.
72    ///
73    /// For example, these bits are used by `sudo`.
74    ///
75    /// Enabling this feature is potentially a security risk because they allow privilege
76    /// escalation.
77    pub enable_suid: bool,
78
79    /// Whether io_uring is enabled.
80    ///
81    /// TODO(https://fxbug.dev/297431387): Enabled by default once the feature is completed.
82    pub io_uring: bool,
83
84    /// Whether the kernel should return an error to userspace, rather than panicking, if `reboot()`
85    /// is requested but cannot be enacted because the kernel lacks the relevant capabilities.
86    pub error_on_failed_reboot: bool,
87
88    /// The default seclabel that is applied to components that are run in this kernel.
89    ///
90    /// Components can override this by setting the `seclabel` field in their program block.
91    pub default_seclabel: Option<String>,
92
93    /// Whether the kernel is being used to run the SELinux Test Suite.
94    ///
95    /// TODO: https://fxbug.dev/388077431 - remove this once we no longer need workarounds for the
96    /// SELinux Test Suite.
97    pub selinux_test_suite: bool,
98
99    /// The default mount options to use when mounting directories from a component's namespace.
100    ///
101    /// The key is the path in the component's namespace, and the value is the mount options
102    /// string.
103    pub default_ns_mount_options: Option<HashMap<String, String>>,
104
105    /// The default uid that is applied to components that are run in this kernel.
106    ///
107    /// Components can override this by setting the `uid` field in their program block.
108    pub default_uid: u32,
109
110    /// mlock() never prefaults pages.
111    pub mlock_always_onfault: bool,
112
113    /// Implementation of mlock() to use for this kernel instance.
114    pub mlock_pin_flavor: MlockPinFlavor,
115
116    /// Whether excessive crash reports should be throttled.
117    pub crash_report_throttling: bool,
118
119    /// Whether or not to serve wifi support to Android.
120    pub wifi: bool,
121
122    /// The number of bytes to cache in pages for reading zx::MapInfo from VMARs.
123    pub cached_zx_map_info_bytes: u32,
124
125    /// The size of the Dirent LRU cache.
126    pub dirent_cache_size: u32,
127}
128
129impl KernelFeatures {
130    /// Returns the `MountParams` to use when mounting the specified path from a component's
131    /// namespace.  This mechanism is also used to specified options for mounts created via
132    /// container features, by specifying a pseudo-path e.g. "#container".
133    pub fn ns_mount_options(&self, ns_path: &str) -> Result<MountParams, Errno> {
134        if let Some(all_options) = &self.default_ns_mount_options {
135            if let Some(options) = all_options.get(ns_path) {
136                return MountParams::parse(options.as_bytes().into());
137            }
138        }
139        Ok(MountParams::default())
140    }
141}
142
143/// Kernel command line argument structure
144pub struct ArgNameAndValue<'a> {
145    pub name: &'a str,
146    pub value: Option<&'a str>,
147}
148
149/// The shared, mutable state for the entire Starnix kernel.
150///
151/// The `Kernel` object holds all kernel threads, userspace tasks, and file system resources for a
152/// single instance of the Starnix kernel. In production, there is one instance of this object for
153/// the entire Starnix kernel. However, multiple instances of this object can be created in one
154/// process during unit testing.
155///
156/// The structure of this object will likely need to evolve as we implement more namespacing and
157/// isolation mechanisms, such as `namespaces(7)` and `pid_namespaces(7)`.
158pub struct Kernel {
159    /// Weak reference to self. Allows to not have to pass &Arc<Kernel> in apis.
160    pub weak_self: Weak<Kernel>,
161
162    /// The kernel threads running on behalf of this kernel.
163    pub kthreads: KernelThreads,
164
165    /// The features enabled for this kernel.
166    pub features: KernelFeatures,
167
168    /// The processes and threads running in this kernel, organized by pid_t.
169    pub pids: RwLock<PidTable>,
170
171    /// Used to record the pid/tid to Koid mappings. Set when collecting trace data.
172    pub pid_to_koid_mapping: Arc<RwLock<Option<PidToKoidMap>>>,
173
174    /// Subsystem-specific properties that hang off the Kernel object.
175    ///
176    /// Instead of adding yet another property to the Kernel object, consider storing the property
177    /// in an expando if that property is only used by one part of the system, such as a module.
178    pub expando: Expando,
179
180    /// The default namespace for abstract AF_UNIX sockets in this kernel.
181    ///
182    /// Rather than use this default namespace, abstract socket addresses
183    /// should be looked up in the AbstractSocketNamespace on each Task
184    /// object because some Task objects might have a non-default namespace.
185    pub default_abstract_socket_namespace: Arc<AbstractUnixSocketNamespace>,
186
187    /// The default namespace for abstract AF_VSOCK sockets in this kernel.
188    pub default_abstract_vsock_namespace: Arc<AbstractVsockSocketNamespace>,
189
190    /// The kernel command line. Shows up in /proc/cmdline.
191    pub cmdline: BString,
192
193    pub device_tree: Option<Devicetree>,
194
195    // Global state held by the Linux Security Modules subsystem.
196    pub security_state: security::KernelState,
197
198    /// The registry of device drivers.
199    pub device_registry: DeviceRegistry,
200
201    /// Mapping of top-level namespace entries to an associated proxy.
202    /// For example, "/svc" to the respective proxy. Only the namespace entries
203    /// which were known at component startup will be available by the kernel.
204    pub container_namespace: ContainerNamespace,
205
206    /// The registry of block devices backed by a remote fuchsia.io file.
207    pub remote_block_device_registry: Arc<RemoteBlockDeviceRegistry>,
208
209    /// The iptables used for filtering network packets.
210    iptables: OnceLock<IpTables>,
211
212    /// The futexes shared across processes.
213    pub shared_futexes: Arc<FutexTable<SharedFutexKey>>,
214
215    /// The default UTS namespace for all tasks.
216    ///
217    /// Because each task can have its own UTS namespace, you probably want to use
218    /// the UTS namespace handle of the task, which may/may not point to this one.
219    pub root_uts_ns: UtsNamespaceHandle,
220
221    /// A struct containing a VMO with a vDSO implementation, if implemented for a given architecture, and possibly an offset for a sigreturn function.
222    pub vdso: Vdso,
223
224    /// A struct containing a VMO with a arch32-vDSO implementation, if implemented for a given architecture.
225    // TODO(https://fxbug.dev/380431743) This could be made less clunky -- maybe a Vec<Vdso> above or
226    // something else
227    pub vdso_arch32: Option<Vdso>,
228
229    /// The table of devices installed on the netstack and their associated
230    /// state local to this `Kernel`.
231    pub netstack_devices: Arc<NetstackDevices>,
232
233    /// Files that are currently available for swapping.
234    /// Note: Starnix never actually swaps memory to these files. We just need to track them
235    /// to pass conformance tests.
236    pub swap_files: OrderedMutex<Vec<FsNodeHandle>, KernelSwapFiles>,
237
238    /// The implementation of generic Netlink protocol families.
239    generic_netlink: OnceLock<GenericNetlink<NetlinkToClientSender<GenericMessage>>>,
240
241    /// The implementation of networking-related Netlink protocol families.
242    network_netlink: OnceLock<Netlink<NetlinkContextImpl>>,
243
244    /// Inspect instrumentation for this kernel instance.
245    pub inspect_node: fuchsia_inspect::Node,
246
247    /// The kinds of seccomp action that gets logged, stored as a bit vector.
248    /// Each potential SeccompAction gets a bit in the vector, as specified by
249    /// SeccompAction::logged_bit_offset.  If the bit is set, that means the
250    /// action should be logged when it is taken, subject to the caveats
251    /// described in seccomp(2).  The value of the bit vector is exposed to users
252    /// in a text form in the file /proc/sys/kernel/seccomp/actions_logged.
253    pub actions_logged: AtomicU16,
254
255    /// The manager for suspend/resume.
256    pub suspend_resume_manager: SuspendResumeManagerHandle,
257
258    /// Unique IDs for new mounts and mount namespaces.
259    pub next_mount_id: AtomicU64Counter,
260    pub next_peer_group_id: AtomicU64Counter,
261    pub next_namespace_id: AtomicU64Counter,
262
263    /// Unique IDs for file objects.
264    pub next_file_object_id: AtomicU64Counter,
265
266    /// Unique cookie used to link two inotify events, usually an IN_MOVE_FROM/IN_MOVE_TO pair.
267    pub next_inotify_cookie: AtomicU32Counter,
268
269    /// Controls which processes a process is allowed to ptrace.  See Documentation/security/Yama.txt
270    pub ptrace_scope: AtomicU8,
271
272    // The Fuchsia build version returned by `fuchsia.buildinfo.Provider`.
273    pub build_version: OnceCell<String>,
274
275    pub stats: Arc<KernelStats>,
276
277    /// Resource limits that are exposed, for example, via sysctl.
278    pub system_limits: SystemLimits,
279
280    // The service to handle delayed releases. This is required for elements that requires to
281    // execute some code when released and requires a known context (both in term of lock context,
282    // as well as `CurrentTask`).
283    pub delayed_releaser: DelayedReleaser,
284
285    /// Manages task priorities.
286    pub scheduler: SchedulerManager,
287
288    /// The syslog manager.
289    pub syslog: Syslog,
290
291    /// All mounts.
292    pub mounts: Mounts,
293
294    /// The manager for creating and managing high-resolution timers.
295    pub hrtimer_manager: HrTimerManagerHandle,
296
297    /// The manager for monitoring and reporting resources used by the kernel.
298    pub memory_attribution_manager: MemoryAttributionManager,
299
300    /// Handler for crashing Linux processes.
301    pub crash_reporter: CrashReporter,
302
303    /// Whether this kernel is shutting down. When shutting down, new processes may not be spawned.
304    shutting_down: AtomicBool,
305
306    /// True to disable syslog access to unprivileged callers.  This also controls whether read
307    /// access to /dev/kmsg requires privileged capabilities.
308    pub restrict_dmesg: AtomicBool,
309
310    /// Determines whether unprivileged BPF is permitted, or can be re-enabled.
311    ///   0 - Unprivileged BPF is permitted.
312    ///   1 - Unprivileged BPF is not permitted, and cannot be enabled.
313    ///   2 - Unprivileged BPF is not permitted, but can be enabled by a privileged task.
314    pub disable_unprivileged_bpf: AtomicU8,
315
316    /// Control handle to the running container's ComponentController.
317    pub container_control_handle: Mutex<Option<ComponentControllerControlHandle>>,
318
319    /// eBPF state: loaded programs, eBPF maps, etc.
320    pub ebpf_state: EbpfState,
321
322    /// Cgroups of the kernel.
323    pub cgroups: KernelCgroups,
324
325    /// Used to communicate requests to adjust system time from within a Starnix
326    /// container. Used from syscalls.
327    pub time_adjustment_proxy: Option<AdjustSynchronousProxy>,
328
329    /// Used to store tokens for sockets, particularly per-uid sharing domain sockets.
330    pub socket_tokens_store: SocketTokensStore,
331
332    /// Hardware capabilities to push onto stack when loading an ELF binary.
333    pub hwcaps: HwCaps,
334}
335
336/// Hardware capabilities.
337#[derive(Debug, Clone, Copy, Default)]
338pub struct HwCap {
339    /// The value for `AT_HWCAP`.
340    pub hwcap: u32,
341    /// The value for `AT_HWCAP2`.
342    pub hwcap2: u32,
343}
344
345/// Hardware capabilities for both 32-bit and 64-bit ELF binaries.
346#[derive(Debug, Clone, Copy, Default)]
347pub struct HwCaps {
348    /// For 32-bit binaries.
349    #[cfg(target_arch = "aarch64")]
350    pub arch32: HwCap,
351    /// For 64-bit binaries.
352    pub arch64: HwCap,
353}
354
355/// An implementation of [`InterfacesHandler`].
356///
357/// This holds a `Weak<Kernel>` because it is held within a [`Netlink`] which
358/// is itself held within an `Arc<Kernel>`. Holding an `Arc<T>` within an
359/// `Arc<T>` prevents the `Arc`'s ref count from ever reaching 0, causing a
360/// leak.
361struct InterfacesHandlerImpl(Weak<Kernel>);
362
363impl InterfacesHandlerImpl {
364    fn kernel(&self) -> Option<Arc<Kernel>> {
365        self.0.upgrade()
366    }
367}
368
369impl InterfacesHandler for InterfacesHandlerImpl {
370    fn handle_new_link(&mut self, name: &str, interface_id: NonZeroU64) {
371        if let Some(kernel) = self.kernel() {
372            kernel.netstack_devices.add_device(&kernel, name.into(), interface_id);
373        }
374    }
375
376    fn handle_deleted_link(&mut self, name: &str) {
377        if let Some(kernel) = self.kernel() {
378            kernel.netstack_devices.remove_device(&kernel, name.into());
379        }
380    }
381
382    fn handle_idle_event(&mut self) {
383        let Some(kernel) = self.kernel() else {
384            log_error!("kernel went away while netlink is initializing");
385            return;
386        };
387        let (initialized, wq) = &kernel.netstack_devices.initialized_and_wq;
388        if initialized.swap(true, Ordering::SeqCst) {
389            log_error!("netlink initial devices should only be reported once");
390            return;
391        }
392        wq.notify_all()
393    }
394}
395
396impl Kernel {
397    pub fn new(
398        cmdline: BString,
399        features: KernelFeatures,
400        system_limits: SystemLimits,
401        container_namespace: ContainerNamespace,
402        scheduler: SchedulerManager,
403        crash_reporter_proxy: Option<CrashReporterProxy>,
404        inspect_node: fuchsia_inspect::Node,
405        security_state: security::KernelState,
406        time_adjustment_proxy: Option<AdjustSynchronousProxy>,
407        device_tree: Option<Devicetree>,
408    ) -> Result<Arc<Kernel>, zx::Status> {
409        let unix_address_maker =
410            Box::new(|x: FsString| -> SocketAddress { SocketAddress::Unix(x) });
411        let vsock_address_maker = Box::new(|x: u32| -> SocketAddress {
412            SocketAddress::Vsock { port: x, cid: VMADDR_CID_HOST }
413        });
414
415        let crash_reporter = CrashReporter::new(
416            &inspect_node,
417            crash_reporter_proxy,
418            zx::Duration::from_minutes(8),
419            features.crash_report_throttling,
420        );
421        let hrtimer_manager = HrTimerManager::new(&inspect_node);
422
423        let cpu_feature_flags =
424            zx::system_get_feature_flags::<CpuFeatureFlags>().unwrap_or_else(|e| {
425                log_debug!("CPU feature flags are only supported on ARM64: {}, reporting 0", e);
426                CpuFeatureFlags::empty()
427            });
428        let hwcaps = HwCaps::from_cpu_feature_flags(cpu_feature_flags);
429
430        let this = Arc::new_cyclic(|kernel| Kernel {
431            weak_self: kernel.clone(),
432            kthreads: KernelThreads::new(kernel.clone()),
433            features,
434            pids: Default::default(),
435            pid_to_koid_mapping: Arc::new(RwLock::new(None)),
436            expando: Default::default(),
437            default_abstract_socket_namespace: AbstractUnixSocketNamespace::new(unix_address_maker),
438            default_abstract_vsock_namespace: AbstractVsockSocketNamespace::new(
439                vsock_address_maker,
440            ),
441            cmdline,
442            device_tree,
443            security_state,
444            device_registry: Default::default(),
445            container_namespace,
446            remote_block_device_registry: Default::default(),
447            iptables: OnceLock::new(),
448            shared_futexes: Arc::<FutexTable<SharedFutexKey>>::default(),
449            root_uts_ns: Arc::new(RwLock::new(UtsNamespace::default())),
450            vdso: Vdso::new(),
451            vdso_arch32: Vdso::new_arch32(),
452            netstack_devices: Arc::default(),
453            swap_files: Default::default(),
454            generic_netlink: OnceLock::new(),
455            network_netlink: OnceLock::new(),
456            inspect_node,
457            actions_logged: AtomicU16::new(0),
458            suspend_resume_manager: Default::default(),
459            next_mount_id: AtomicU64Counter::new(1),
460            next_peer_group_id: AtomicU64Counter::new(1),
461            next_namespace_id: AtomicU64Counter::new(1),
462            next_inotify_cookie: AtomicU32Counter::new(1),
463            next_file_object_id: Default::default(),
464            system_limits,
465            ptrace_scope: AtomicU8::new(0), // Disable YAMA checks by default.
466            restrict_dmesg: AtomicBool::new(false),
467            disable_unprivileged_bpf: AtomicU8::new(0), // Enable unprivileged BPF by default.
468            build_version: OnceCell::new(),
469            stats: Arc::new(KernelStats::default()),
470            delayed_releaser: Default::default(),
471            scheduler,
472            syslog: Default::default(),
473            mounts: Mounts::new(),
474            hrtimer_manager,
475            memory_attribution_manager: MemoryAttributionManager::new(kernel.clone()),
476            crash_reporter,
477            shutting_down: AtomicBool::new(false),
478            container_control_handle: Mutex::new(None),
479            ebpf_state: Default::default(),
480            cgroups: Default::default(),
481            time_adjustment_proxy,
482            socket_tokens_store: Default::default(),
483            hwcaps,
484        });
485
486        // Initialize the device registry before registering any devices.
487        //
488        // We will create sysfs recursively within this function.
489        this.device_registry.objects.init(&mut this.kthreads.unlocked_for_async(), &this);
490
491        // Make a copy of this Arc for the inspect lazy node to use but don't create an Arc cycle
492        // because the inspect node that owns this reference is owned by the kernel.
493        let kernel = Arc::downgrade(&this);
494        this.inspect_node.record_lazy_child("thread_groups", move || {
495            if let Some(kernel) = kernel.upgrade() {
496                let inspector = kernel.get_thread_groups_inspect();
497                async move { Ok(inspector) }.boxed()
498            } else {
499                async move { Err(anyhow::format_err!("kernel was dropped")) }.boxed()
500            }
501        });
502
503        let kernel = Arc::downgrade(&this);
504        this.inspect_node.record_lazy_child("cgroupv2", move || {
505            if let Some(kernel) = kernel.upgrade() {
506                async move { Ok(kernel.cgroups.cgroup2.get_cgroup_inspect()) }.boxed()
507            } else {
508                async move { Err(anyhow::format_err!("kernel was dropped")) }.boxed()
509            }
510        });
511
512        Ok(this)
513    }
514
515    /// Shuts down userspace and the kernel in an orderly fashion, eventually terminating the root
516    /// kernel process.
517    pub fn shut_down(self: &Arc<Self>) {
518        // Run shutdown code on a kthread in the main process so that it can be the last process
519        // alive.
520        self.kthreads.spawn_future({
521            let kernel = self.clone();
522            async move || {
523                kernel.run_shutdown().await;
524            }
525        });
526    }
527
528    /// Starts shutting down the Starnix kernel and any running container. Only one thread can drive
529    /// shutdown at a time. This function will return immediately if shut down is already under way.
530    ///
531    /// Shutdown happens in several phases:
532    ///
533    /// 1. Disable launching new processes
534    /// 2. Shut down individual ThreadGroups until only the init and system tasks remain
535    /// 3. Repeat the above for the init task
536    /// 4. Clean up kernel-internal structures that can hold processes alive
537    /// 5. Ensure this process is the only one running in the kernel job.
538    /// 6. Unmounts the kernel's mounts' FileSystems.
539    /// 7. Tell CF the container component has stopped
540    /// 8. Exit this process
541    ///
542    /// If a ThreadGroup does not shut down on its own (including after SIGKILL), that phase of
543    /// shutdown will hang. To gracefully shut down any further we need the other kernel processes
544    /// to do controlled exits that properly release access to shared state. If our orderly shutdown
545    /// does hang, eventually CF will kill the container component which will lead to the job of
546    /// this process being killed and shutdown will still complete.
547    async fn run_shutdown(&self) {
548        const INIT_PID: i32 = 1;
549        const SYSTEM_TASK_PID: i32 = 2;
550
551        // Step 1: Prevent new processes from being created once they observe this update. We don't
552        // want the thread driving shutdown to be racing with other threads creating new processes.
553        if self
554            .shutting_down
555            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
556            .is_err()
557        {
558            log_debug!("Additional thread tried to initiate shutdown while already in-progress.");
559            return;
560        }
561
562        log_info!("Shutting down Starnix kernel.");
563
564        // Step 2: Shut down thread groups in a loop until init and the system task are all that
565        // remain.
566        loop {
567            let tgs = {
568                // Exiting thread groups need to acquire a write lock for the pid table to
569                // successfully exit so we need to acquire that lock in a reduced scope.
570                self.pids
571                    .read()
572                    .get_thread_groups()
573                    .filter(|tg| tg.leader != SYSTEM_TASK_PID && tg.leader != INIT_PID)
574                    .collect::<Vec<_>>()
575            };
576            if tgs.is_empty() {
577                log_debug!("pid table is empty except init and system task");
578                break;
579            }
580
581            log_debug!(tgs:?; "shutting down thread groups");
582            let mut tasks = vec![];
583            for tg in tgs {
584                let task = fasync::Task::local(ThreadGroup::shut_down(Arc::downgrade(&tg)));
585                tasks.push(task);
586            }
587            futures::future::join_all(tasks).await;
588        }
589
590        // Step 3: Terminate the init process.
591        let maybe_init = {
592            // Exiting thread groups need to acquire a write lock for the pid table to successfully
593            // exit so we need to acquire that lock in a reduced scope.
594            self.pids.read().get_thread_group(1).map(|tg| Arc::downgrade(&tg))
595        };
596        if let Some(init) = maybe_init {
597            log_debug!("shutting down init");
598            ThreadGroup::shut_down(init).await;
599        } else {
600            log_debug!("init already terminated");
601        }
602
603        // Step 4: Clean up any structures that can keep non-Linux processes live in our job.
604        log_debug!("cleaning up pinned memory");
605        self.expando.remove::<memory_pinning::ShadowProcess>();
606
607        // Step 5: Make sure this is the only process running in the job. We already should have
608        // cleared up all processes other than the system task at this point, but wait on any that
609        // might be around for good measure.
610        //
611        // Use unwrap liberally since we're shutting down anyway and errors will still tear down the
612        // kernel.
613        let kernel_job = fuchsia_runtime::job_default();
614        assert_eq!(kernel_job.children().unwrap(), &[], "starnix does not create any child jobs");
615        let own_koid = fuchsia_runtime::process_self().koid().unwrap();
616
617        log_debug!("waiting for this to be the only process in the job");
618        loop {
619            let mut remaining_processes = kernel_job
620                .processes()
621                .unwrap()
622                .into_iter()
623                // Don't wait for ourselves to exit.
624                .filter(|pid| pid != &own_koid)
625                .peekable();
626            if remaining_processes.peek().is_none() {
627                log_debug!("No stray Zircon processes.");
628                break;
629            }
630
631            let mut terminated_signals = vec![];
632            for pid in remaining_processes {
633                let handle = match kernel_job
634                    .get_child(&pid, zx::Rights::BASIC | zx::Rights::PROPERTY | zx::Rights::DESTROY)
635                {
636                    Ok(h) => h,
637                    Err(e) => {
638                        log_debug!(pid:?, e:?; "failed to get child process from job");
639                        continue;
640                    }
641                };
642                log_debug!(
643                    pid:?,
644                    name:? = handle.get_name();
645                    "waiting on process terminated signal"
646                );
647                terminated_signals
648                    .push(fuchsia_async::OnSignals::new(handle, zx::Signals::PROCESS_TERMINATED));
649            }
650            log_debug!("waiting on process terminated signals");
651            futures::future::join_all(terminated_signals).await;
652        }
653
654        // Step 6: Forcibly unmounts the mounts' FileSystems.
655        log_debug!("clearing mounts");
656        self.mounts.clear();
657
658        // Step 7: Tell CF the container stopped.
659        log_debug!("all non-root processes killed, notifying CF container is stopped");
660        if let Some(control_handle) = self.container_control_handle.lock().take() {
661            log_debug!("Notifying CF that the container has stopped.");
662            control_handle
663                .send_on_stop(ComponentStopInfo {
664                    termination_status: Some(zx::Status::OK.into_raw()),
665                    exit_code: Some(0),
666                    ..ComponentStopInfo::default()
667                })
668                .unwrap();
669            control_handle.shutdown_with_epitaph(zx::Status::OK);
670        } else {
671            log_warn!("Shutdown invoked without a container controller control handle.");
672        }
673
674        // Step 8: exiting this process.
675        log_info!("All tasks killed, exiting Starnix kernel root process.");
676        // Normally a Rust program exits its process by calling `std::process::exit()` which goes
677        // through libc to exit the program. This runs drop impls on any thread-local variables
678        // which can cause issues during Starnix shutdown when we haven't yet integrated every
679        // subsystem with the shutdown flow. While those issues are indicative of underlying
680        // problems, we can't solve them without finishing the implementation of graceful shutdown.
681        // Instead, ask Zircon to exit our process directly, bypassing any libc atexit handlers.
682        // TODO(https://fxbug.dev/295073633) return from main instead of avoiding atexit handlers
683        zx::Process::exit(0);
684    }
685
686    pub fn is_shutting_down(&self) -> bool {
687        self.shutting_down.load(Ordering::Acquire)
688    }
689
690    /// Opens a device file (driver) identified by `dev`.
691    pub fn open_device<L>(
692        &self,
693        locked: &mut Locked<L>,
694        current_task: &CurrentTask,
695        node: &NamespaceNode,
696        flags: OpenFlags,
697        dev: DeviceType,
698        mode: DeviceMode,
699    ) -> Result<Box<dyn FileOps>, Errno>
700    where
701        L: LockEqualOrBefore<FileOpsCore>,
702    {
703        self.device_registry.open_device(locked, current_task, node, flags, dev, mode)
704    }
705
706    /// Return a reference to the Audit Framework
707    ///
708    /// This function follows the lazy initialization pattern.
709    pub fn audit_logger(&self) -> Arc<AuditLogger> {
710        self.expando.get_or_init(|| AuditLogger::new(self))
711    }
712
713    /// Return a reference to the GenericNetlink implementation.
714    ///
715    /// This function follows the lazy initialization pattern, where the first
716    /// call will instantiate the Generic Netlink server in a separate kthread.
717    pub fn generic_netlink(&self) -> &GenericNetlink<NetlinkToClientSender<GenericMessage>> {
718        self.generic_netlink.get_or_init(|| {
719            let (generic_netlink, worker_params) = GenericNetlink::new();
720            let enable_nl80211 = self.features.wifi;
721            self.kthreads.spawn_future(async move || {
722                crate::vfs::socket::run_generic_netlink_worker(worker_params, enable_nl80211).await;
723                log_error!("Generic Netlink future unexpectedly exited");
724            });
725            generic_netlink
726        })
727    }
728
729    /// Return a reference to the [`netlink::Netlink`] implementation.
730    ///
731    /// This function follows the lazy initialization pattern, where the first
732    /// call will instantiate the Netlink implementation.
733    pub fn network_netlink(self: &Arc<Self>) -> &Netlink<NetlinkContextImpl> {
734        self.network_netlink.get_or_init(|| {
735            let (network_netlink, worker_params) =
736                Netlink::new(InterfacesHandlerImpl(self.weak_self.clone()));
737
738            let kernel = self.clone();
739            self.kthreads.spawn_future(async move || {
740                netlink::run_netlink_worker(
741                    worker_params,
742                    NetlinkAccessControl::new(kernel.kthreads.system_task()),
743                )
744                .await;
745                log_error!(tag = NETLINK_LOG_TAG; "Netlink async worker unexpectedly exited");
746            });
747            network_netlink
748        })
749    }
750
751    pub fn iptables(&self) -> &IpTables {
752        self.iptables.get_or_init(|| IpTables::new())
753    }
754
755    /// Returns a Proxy to the service used by the container at `filename`.
756    #[allow(unused)]
757    pub fn connect_to_named_protocol_at_container_svc<P: ProtocolMarker>(
758        &self,
759        filename: &str,
760    ) -> Result<ClientEnd<P>, Errno> {
761        match self.container_namespace.get_namespace_channel("/svc") {
762            Ok(channel) => {
763                let (client_end, server_end) = create_endpoints::<P>();
764                fdio::service_connect_at(channel.as_ref(), filename, server_end.into_channel())
765                    .map_err(|status| from_status_like_fdio!(status))?;
766                Ok(client_end)
767            }
768            Err(err) => {
769                log_error!("Unable to get /svc namespace channel! {}", err);
770                Err(errno!(ENOENT))
771            }
772        }
773    }
774
775    /// Returns a Proxy to the service `P` used by the container.
776    pub fn connect_to_protocol_at_container_svc<P: DiscoverableProtocolMarker>(
777        &self,
778    ) -> Result<ClientEnd<P>, Errno> {
779        self.connect_to_named_protocol_at_container_svc::<P>(P::PROTOCOL_NAME)
780    }
781
782    fn get_thread_groups_inspect(&self) -> fuchsia_inspect::Inspector {
783        let inspector = fuchsia_inspect::Inspector::default();
784
785        let thread_groups = inspector.root();
786        let mut mm_summary = MappingSummary::default();
787        let mut mms_summarized = HashSet::new();
788
789        // Avoid holding locks for the entire iteration.
790        let all_thread_groups = {
791            let pid_table = self.pids.read();
792            pid_table.get_thread_groups().collect::<Vec<_>>()
793        };
794        for thread_group in all_thread_groups {
795            // Avoid holding the state lock while summarizing.
796            let (ppid, tasks) = {
797                let tg = thread_group.read();
798                (tg.get_ppid() as i64, tg.tasks().map(TempRef::into_static).collect::<Vec<_>>())
799            };
800
801            let tg_node = thread_groups.create_child(format!("{}", thread_group.leader));
802            if let Ok(koid) = &thread_group.process.koid() {
803                tg_node.record_int("koid", koid.raw_koid() as i64);
804            }
805            tg_node.record_int("pid", thread_group.leader as i64);
806            tg_node.record_int("ppid", ppid);
807            tg_node.record_bool("stopped", thread_group.load_stopped() == StopState::GroupStopped);
808
809            let tasks_node = tg_node.create_child("tasks");
810            for task in tasks {
811                if let Ok(mm) = task.mm() {
812                    if mms_summarized.insert(Arc::as_ptr(&mm) as usize) {
813                        mm.summarize(&mut mm_summary);
814                    }
815                }
816                let set_properties = |node: &fuchsia_inspect::Node| {
817                    node.record_string("command", task.command().to_string());
818
819                    let scheduler_state = task.read().scheduler_state;
820                    if !scheduler_state.is_default() {
821                        node.record_child("sched", |node| {
822                            node.record_string(
823                                "role_name",
824                                self.scheduler
825                                    .role_name(&task)
826                                    .map(|n| Cow::Borrowed(n))
827                                    .unwrap_or_else(|e| Cow::Owned(e.to_string())),
828                            );
829                            node.record_string("state", format!("{scheduler_state:?}"));
830                        });
831                    }
832                };
833                if task.tid == thread_group.leader {
834                    let mut argv = task.read_argv(256).unwrap_or_default();
835
836                    // Any runtime that overwrites argv is likely to leave a lot of trailing
837                    // nulls, no need to print those in inspect.
838                    argv.retain(|arg| !arg.is_empty());
839
840                    let inspect_argv = tg_node.create_string_array("argv", argv.len());
841                    for (i, arg) in argv.iter().enumerate() {
842                        inspect_argv.set(i, arg.to_string());
843                    }
844                    tg_node.record(inspect_argv);
845
846                    set_properties(&tg_node);
847                } else {
848                    tasks_node.record_child(task.tid.to_string(), |task_node| {
849                        set_properties(task_node);
850                    });
851                };
852            }
853            tg_node.record(tasks_node);
854            thread_groups.record(tg_node);
855        }
856
857        thread_groups.record_child("memory_managers", |node| mm_summary.record(node));
858
859        inspector
860    }
861
862    pub fn new_memory_attribution_observer(
863        &self,
864        control_handle: fattribution::ProviderControlHandle,
865    ) -> attribution_server::Observer {
866        self.memory_attribution_manager.new_observer(control_handle)
867    }
868
869    /// Opens and returns a directory proxy from the container's namespace, at
870    /// the requested path, using the provided flags. This method will open the
871    /// closest existing path from the namespace hierarchy, and then attempt
872    /// initialize an open on the remaining subdirectory path, using the given open_flags.
873    ///
874    /// For example, given the parameter provided is `/path/to/foo/bar` and there
875    /// are namespace entries already for `/path/to/foo` and `/path/to`. The entry
876    /// for /path/to/foo will be opened, and then the /bar will attempt to be opened
877    /// underneath that directory with the given open_flags. The returned value
878    /// will be the proxy to the parent (/path/to/foo) and the string to the child
879    /// path (/bar). The caller of this method can expect /bar to be initialized.
880    pub fn open_ns_dir(
881        &self,
882        path: &str,
883        open_flags: fio::Flags,
884    ) -> Result<(fio::DirectorySynchronousProxy, String), Errno> {
885        let ns_path = PathBuf::from(path);
886        match self.container_namespace.find_closest_channel(&ns_path) {
887            Ok((root_channel, remaining_subdir)) => {
888                let (_, server_end) = create_endpoints::<fio::DirectoryMarker>();
889                fdio::open_at(
890                    &root_channel,
891                    &remaining_subdir,
892                    open_flags,
893                    server_end.into_channel(),
894                )
895                .map_err(|e| {
896                    log_error!("Failed to intialize the subdirs: {}", e);
897                    errno!(EIO)
898                })?;
899
900                Ok((fio::DirectorySynchronousProxy::new(root_channel), remaining_subdir))
901            }
902            Err(err) => {
903                log_error!(
904                    "Unable to find a channel for {}. Received error: {}",
905                    ns_path.display(),
906                    err
907                );
908                Err(errno!(ENOENT))
909            }
910        }
911    }
912
913    /// Returns an iterator of the command line arguments.
914    pub fn cmdline_args_iter(&self) -> impl Iterator<Item = ArgNameAndValue<'_>> {
915        parse_cmdline(self.cmdline.to_str().unwrap_or_default()).filter_map(|arg| {
916            arg.split_once('=')
917                .map(|(name, value)| ArgNameAndValue { name: name, value: Some(value) })
918                .or(Some(ArgNameAndValue { name: arg, value: None }))
919        })
920    }
921
922    /// Returns the container-configured CacheConfig.
923    pub fn fs_cache_config(&self) -> CacheConfig {
924        CacheConfig { capacity: self.features.dirent_cache_size as usize }
925    }
926}
927
928pub fn parse_cmdline(cmdline: &str) -> impl Iterator<Item = &str> {
929    let mut args = Vec::new();
930    let mut arg_start: Option<usize> = None;
931    let mut in_quotes = false;
932    let mut previous_char = ' ';
933
934    for (i, c) in cmdline.char_indices() {
935        if let Some(start) = arg_start {
936            match c {
937                ' ' if !in_quotes => {
938                    args.push(&cmdline[start..i]);
939                    arg_start = None;
940                }
941                '"' if previous_char != '\\' => {
942                    in_quotes = !in_quotes;
943                }
944                _ => {}
945            }
946        } else if c != ' ' {
947            arg_start = Some(i);
948            if c == '"' {
949                in_quotes = true;
950            }
951        }
952        previous_char = c;
953    }
954    if let Some(start) = arg_start {
955        args.push(&cmdline[start..]);
956    }
957    args.into_iter()
958}
959
960impl std::fmt::Debug for Kernel {
961    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
962        f.debug_struct("Kernel").finish()
963    }
964}
965
966// TODO(https://fxbug.dev/380427153): move arch dependent code to `kernel/core/arch/*`.
967#[cfg(target_arch = "aarch64")]
968fn arm32_hwcap(cpu_feature_flags: CpuFeatureFlags) -> HwCap {
969    use starnix_uapi::arch32;
970    const COMPAT_ARM32_ELF_HWCAP: u32 = arch32::HWCAP_HALF
971        | arch32::HWCAP_THUMB
972        | arch32::HWCAP_FAST_MULT
973        | arch32::HWCAP_EDSP
974        | arch32::HWCAP_TLS
975        | arch32::HWCAP_IDIV // == IDIVA | IDIVT.
976        | arch32::HWCAP_LPAE
977        | arch32::HWCAP_EVTSTRM;
978
979    let mut hwcap = COMPAT_ARM32_ELF_HWCAP;
980    let mut hwcap2 = 0;
981    for feature in cpu_feature_flags.iter() {
982        match feature {
983            CpuFeatureFlags::ARM64_FEATURE_ISA_ASIMD => hwcap |= arch32::HWCAP_NEON,
984            CpuFeatureFlags::ARM64_FEATURE_ISA_AES => hwcap2 |= arch32::HWCAP2_AES,
985            CpuFeatureFlags::ARM64_FEATURE_ISA_PMULL => hwcap2 |= arch32::HWCAP2_PMULL,
986            CpuFeatureFlags::ARM64_FEATURE_ISA_SHA1 => hwcap2 |= arch32::HWCAP2_SHA1,
987            CpuFeatureFlags::ARM64_FEATURE_ISA_SHA256 => hwcap2 |= arch32::HWCAP2_SHA2,
988            CpuFeatureFlags::ARM64_FEATURE_ISA_CRC32 => hwcap2 |= arch32::HWCAP2_CRC32,
989            CpuFeatureFlags::ARM64_FEATURE_ISA_I8MM => hwcap |= arch32::HWCAP_I8MM,
990            CpuFeatureFlags::ARM64_FEATURE_ISA_FHM => hwcap |= arch32::HWCAP_ASIMDFHM,
991            CpuFeatureFlags::ARM64_FEATURE_ISA_DP => hwcap |= arch32::HWCAP_ASIMDDP,
992            CpuFeatureFlags::ARM64_FEATURE_ISA_FP => {
993                hwcap |= arch32::HWCAP_VFP | arch32::HWCAP_VFPv3 | arch32::HWCAP_VFPv4
994            }
995            _ => {}
996        }
997    }
998    HwCap { hwcap, hwcap2 }
999}
1000
1001#[cfg(target_arch = "aarch64")]
1002fn arm64_hwcap(cpu_feature_flags: CpuFeatureFlags) -> HwCap {
1003    // See https://docs.kernel.org/arch/arm64/elf_hwcaps.html for details.
1004    use starnix_uapi;
1005    let mut hwcap = 0;
1006    let mut hwcap2 = 0;
1007
1008    for feature in cpu_feature_flags.iter() {
1009        match feature {
1010            CpuFeatureFlags::ARM64_FEATURE_ISA_FP => hwcap |= starnix_uapi::HWCAP_FP,
1011            CpuFeatureFlags::ARM64_FEATURE_ISA_ASIMD => hwcap |= starnix_uapi::HWCAP_ASIMD,
1012            CpuFeatureFlags::ARM64_FEATURE_ISA_AES => hwcap |= starnix_uapi::HWCAP_AES,
1013            CpuFeatureFlags::ARM64_FEATURE_ISA_PMULL => hwcap |= starnix_uapi::HWCAP_PMULL,
1014            CpuFeatureFlags::ARM64_FEATURE_ISA_SHA1 => hwcap |= starnix_uapi::HWCAP_SHA1,
1015            CpuFeatureFlags::ARM64_FEATURE_ISA_SHA256 => hwcap |= starnix_uapi::HWCAP_SHA2,
1016            CpuFeatureFlags::ARM64_FEATURE_ISA_CRC32 => hwcap |= starnix_uapi::HWCAP_CRC32,
1017            CpuFeatureFlags::ARM64_FEATURE_ISA_I8MM => hwcap2 |= starnix_uapi::HWCAP2_I8MM,
1018            CpuFeatureFlags::ARM64_FEATURE_ISA_FHM => hwcap |= starnix_uapi::HWCAP_ASIMDFHM,
1019            CpuFeatureFlags::ARM64_FEATURE_ISA_DP => hwcap |= starnix_uapi::HWCAP_ASIMDDP,
1020            CpuFeatureFlags::ARM64_FEATURE_ISA_SM3 => hwcap |= starnix_uapi::HWCAP_SM3,
1021            CpuFeatureFlags::ARM64_FEATURE_ISA_SM4 => hwcap |= starnix_uapi::HWCAP_SM4,
1022            CpuFeatureFlags::ARM64_FEATURE_ISA_SHA3 => hwcap |= starnix_uapi::HWCAP_SHA3,
1023            CpuFeatureFlags::ARM64_FEATURE_ISA_SHA512 => hwcap |= starnix_uapi::HWCAP_SHA512,
1024            CpuFeatureFlags::ARM64_FEATURE_ISA_ATOMICS => hwcap |= starnix_uapi::HWCAP_ATOMICS,
1025            CpuFeatureFlags::ARM64_FEATURE_ISA_RDM => hwcap |= starnix_uapi::HWCAP_ASIMDRDM,
1026            CpuFeatureFlags::ARM64_FEATURE_ISA_TS => hwcap |= starnix_uapi::HWCAP_FLAGM,
1027            CpuFeatureFlags::ARM64_FEATURE_ISA_DPB => hwcap |= starnix_uapi::HWCAP_DCPOP,
1028            CpuFeatureFlags::ARM64_FEATURE_ISA_RNDR => hwcap2 |= starnix_uapi::HWCAP2_RNG,
1029            _ => {}
1030        }
1031    }
1032    HwCap { hwcap, hwcap2 }
1033}
1034
1035impl HwCaps {
1036    #[cfg(target_arch = "aarch64")]
1037    pub fn from_cpu_feature_flags(cpu_feature_flags: CpuFeatureFlags) -> Self {
1038        Self { arch32: arm32_hwcap(cpu_feature_flags), arch64: arm64_hwcap(cpu_feature_flags) }
1039    }
1040
1041    #[cfg(not(target_arch = "aarch64"))]
1042    pub fn from_cpu_feature_flags(_cpu_feature_flags: CpuFeatureFlags) -> Self {
1043        Self { arch64: HwCap::default() }
1044    }
1045}
1046
1047#[cfg(test)]
1048mod test {
1049    use super::parse_cmdline;
1050
1051    #[test]
1052    fn test_parse_cmdline() {
1053        let cmdline =
1054            r#"first second=third "fourth fifth" sixth="seventh eighth" "ninth\" tenth" eleventh"#;
1055        let expected = vec![
1056            "first",
1057            "second=third",
1058            "\"fourth fifth\"",
1059            "sixth=\"seventh eighth\"",
1060            "\"ninth\\\" tenth\"",
1061            "eleventh",
1062        ];
1063        assert_eq!(parse_cmdline(cmdline).collect::<Vec<_>>(), expected);
1064    }
1065}