1use 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 pub enable_suid: bool,
78
79 pub io_uring: bool,
83
84 pub error_on_failed_reboot: bool,
87
88 pub default_seclabel: Option<String>,
92
93 pub selinux_test_suite: bool,
98
99 pub default_ns_mount_options: Option<HashMap<String, String>>,
104
105 pub default_uid: u32,
109
110 pub mlock_always_onfault: bool,
112
113 pub mlock_pin_flavor: MlockPinFlavor,
115
116 pub crash_report_throttling: bool,
118
119 pub wifi: bool,
121
122 pub cached_zx_map_info_bytes: u32,
124
125 pub dirent_cache_size: u32,
127}
128
129impl KernelFeatures {
130 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
143pub struct ArgNameAndValue<'a> {
145 pub name: &'a str,
146 pub value: Option<&'a str>,
147}
148
149pub struct Kernel {
159 pub weak_self: Weak<Kernel>,
161
162 pub kthreads: KernelThreads,
164
165 pub features: KernelFeatures,
167
168 pub pids: RwLock<PidTable>,
170
171 pub pid_to_koid_mapping: Arc<RwLock<Option<PidToKoidMap>>>,
173
174 pub expando: Expando,
179
180 pub default_abstract_socket_namespace: Arc<AbstractUnixSocketNamespace>,
186
187 pub default_abstract_vsock_namespace: Arc<AbstractVsockSocketNamespace>,
189
190 pub cmdline: BString,
192
193 pub device_tree: Option<Devicetree>,
194
195 pub security_state: security::KernelState,
197
198 pub device_registry: DeviceRegistry,
200
201 pub container_namespace: ContainerNamespace,
205
206 pub remote_block_device_registry: Arc<RemoteBlockDeviceRegistry>,
208
209 iptables: OnceLock<IpTables>,
211
212 pub shared_futexes: Arc<FutexTable<SharedFutexKey>>,
214
215 pub root_uts_ns: UtsNamespaceHandle,
220
221 pub vdso: Vdso,
223
224 pub vdso_arch32: Option<Vdso>,
228
229 pub netstack_devices: Arc<NetstackDevices>,
232
233 pub swap_files: OrderedMutex<Vec<FsNodeHandle>, KernelSwapFiles>,
237
238 generic_netlink: OnceLock<GenericNetlink<NetlinkToClientSender<GenericMessage>>>,
240
241 network_netlink: OnceLock<Netlink<NetlinkContextImpl>>,
243
244 pub inspect_node: fuchsia_inspect::Node,
246
247 pub actions_logged: AtomicU16,
254
255 pub suspend_resume_manager: SuspendResumeManagerHandle,
257
258 pub next_mount_id: AtomicU64Counter,
260 pub next_peer_group_id: AtomicU64Counter,
261 pub next_namespace_id: AtomicU64Counter,
262
263 pub next_file_object_id: AtomicU64Counter,
265
266 pub next_inotify_cookie: AtomicU32Counter,
268
269 pub ptrace_scope: AtomicU8,
271
272 pub build_version: OnceCell<String>,
274
275 pub stats: Arc<KernelStats>,
276
277 pub system_limits: SystemLimits,
279
280 pub delayed_releaser: DelayedReleaser,
284
285 pub scheduler: SchedulerManager,
287
288 pub syslog: Syslog,
290
291 pub mounts: Mounts,
293
294 pub hrtimer_manager: HrTimerManagerHandle,
296
297 pub memory_attribution_manager: MemoryAttributionManager,
299
300 pub crash_reporter: CrashReporter,
302
303 shutting_down: AtomicBool,
305
306 pub restrict_dmesg: AtomicBool,
309
310 pub disable_unprivileged_bpf: AtomicU8,
315
316 pub container_control_handle: Mutex<Option<ComponentControllerControlHandle>>,
318
319 pub ebpf_state: EbpfState,
321
322 pub cgroups: KernelCgroups,
324
325 pub time_adjustment_proxy: Option<AdjustSynchronousProxy>,
328
329 pub socket_tokens_store: SocketTokensStore,
331
332 pub hwcaps: HwCaps,
334}
335
336#[derive(Debug, Clone, Copy, Default)]
338pub struct HwCap {
339 pub hwcap: u32,
341 pub hwcap2: u32,
343}
344
345#[derive(Debug, Clone, Copy, Default)]
347pub struct HwCaps {
348 #[cfg(target_arch = "aarch64")]
350 pub arch32: HwCap,
351 pub arch64: HwCap,
353}
354
355struct 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), restrict_dmesg: AtomicBool::new(false),
467 disable_unprivileged_bpf: AtomicU8::new(0), 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 this.device_registry.objects.init(&mut this.kthreads.unlocked_for_async(), &this);
490
491 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 pub fn shut_down(self: &Arc<Self>) {
518 self.kthreads.spawn_future({
521 let kernel = self.clone();
522 async move || {
523 kernel.run_shutdown().await;
524 }
525 });
526 }
527
528 async fn run_shutdown(&self) {
548 const INIT_PID: i32 = 1;
549 const SYSTEM_TASK_PID: i32 = 2;
550
551 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 loop {
567 let tgs = {
568 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 let maybe_init = {
592 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 log_debug!("cleaning up pinned memory");
605 self.expando.remove::<memory_pinning::ShadowProcess>();
606
607 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 .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 log_debug!("clearing mounts");
656 self.mounts.clear();
657
658 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 log_info!("All tasks killed, exiting Starnix kernel root process.");
676 zx::Process::exit(0);
684 }
685
686 pub fn is_shutting_down(&self) -> bool {
687 self.shutting_down.load(Ordering::Acquire)
688 }
689
690 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 pub fn audit_logger(&self) -> Arc<AuditLogger> {
710 self.expando.get_or_init(|| AuditLogger::new(self))
711 }
712
713 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 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 #[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 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 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 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 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 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 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 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#[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 | 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 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}