1use alloc::{
2 string::{String, ToString},
3 sync::Arc,
4};
5
6use ax_fs_ng::vfs::current_fs_context;
7use ax_runtime::hal::cpu::user::UserContext;
8
9use crate::{
10 file::{FD_TABLE, FileTable, new_file_table_scope},
11 mm::{MmHandle, load_user_app, new_user_image_builder},
12 namespace::NsProxy,
13 pseudofs::{self, dev::tty},
14 sync::{Mutex, RwLock},
15 task::{
16 PidReservation, PidReservationKind, Process, ProcessData, ProcessDataInit, ProcessImage,
17 ROOT_PID_NS, Tgid, Thread, Tid, TidNumber, UserThreadOptions, kernel_thread_builder,
18 new_user_task, prepare_user_thread, sleep, spawn_alarm_task,
19 },
20 tracepoint::tracepoint_init,
21};
22
23pub fn init(args: &[String], envs: &[String]) {
25 crate::stop_machine::init();
26 crate::trap::init_handlers();
27 static_keys::global_init();
28 crate::cgroup::init();
29
30 tracepoint_init().expect("Failed to initialize tracepoints");
31
32 crate::ebpf::init_ebpf();
33 crate::perf::perf_event_init();
34 crate::kmod::init_kmod();
35
36 pseudofs::mount_all().expect("Failed to mount pseudofs");
37 spawn_alarm_task();
38 crate::mm::spawn_reclaimer_task();
39 if ax_driver::cpufreq::calibrate_wanted() {
43 run_opp_calibration();
44 } else {
45 spawn_cpufreq_governor();
46 }
47 ax_driver::cpufreq::log_frequency_readout();
49 pseudofs::usbfs::start_event_pump();
50
51 ax_alloc::register_page_reclaim_fn(ax_fs_ng::vfs::page_cache_reclaim);
52
53 let loc = current_fs_context()
54 .lock()
55 .resolve(&args[0])
56 .expect("Failed to resolve executable path");
57 let path = loc
58 .absolute_path()
59 .expect("Failed to get executable absolute path");
60 let name = loc.name().into_owned();
61
62 let mut image_builder =
63 new_user_image_builder().expect("Failed to create unpublished user address space");
64 let loaded_image = load_user_app(
65 &mut image_builder,
66 loc,
67 &args[0],
68 args,
69 envs,
70 &crate::task::Cred::root(),
71 )
72 .unwrap_or_else(|error| panic!("Failed to load user app: {error}"));
73 let prepared_image = image_builder
74 .finish(loaded_image)
75 .expect("loaded init image token no longer matches its address space");
76 let (uspace, entry_vaddr, ustack_top, auxv) = prepared_image.into_parts();
77
78 let uctx = UserContext::new(entry_vaddr.into(), ustack_top, 0);
79
80 const INIT_PID: u32 = 1;
89 let reservation = PidReservation::reserve(&ROOT_PID_NS, PidReservationKind::ProcessLeader)
90 .expect("failed to reserve init PID identity");
91 let pid = reservation
92 .number_in(&ROOT_PID_NS)
93 .expect("init PID reservation has no root binding")
94 .get();
95 assert_eq!(pid, INIT_PID);
96 let identity = reservation.identity();
97 let tid_lease = identity
98 .acquire_role::<Tid>()
99 .expect("failed to acquire init TID role");
100 let tgid_lease = identity
101 .acquire_role::<Tgid>()
102 .expect("failed to acquire init TGID role");
103 let proc = Process::new_init(identity.clone()).expect("failed to prepare init process");
104 proc.add_thread(TidNumber::try_from(pid).expect("init TID must be non-zero"));
105
106 if let Err(error) = tty::bind_console_to(&proc) {
107 warn!("Failed to bind console tty: {error:?}");
108 }
109
110 let proc = ProcessData::new(
111 proc,
112 identity.clone(),
113 tgid_lease,
114 ProcessDataInit::new(
115 ProcessImage::new(
116 path.to_string(),
117 Arc::new(args.to_vec()),
118 Arc::new(envs.to_vec()),
119 auxv,
120 "/".to_string(),
121 "/".to_string(),
122 ),
123 MmHandle::from_arc(Arc::new(Mutex::new(uspace)))
124 .expect("init MM identity must be unique"),
125 Arc::default(),
126 NsProxy::new_root(),
127 None,
128 TidNumber::try_from(pid).expect("init TID must be non-zero"),
129 ),
130 );
131 crate::cgroup::attach_initial_process(&identity)
133 .expect("Failed to attach init process to cgroup root");
134
135 let mut scope = scope_local::Scope::new();
136 let mut fd_table = FileTable::new();
137 crate::file::add_stdio(&mut fd_table).expect("Failed to add stdio");
138 *FD_TABLE.scope_mut(&mut scope) = new_file_table_scope(Arc::new(RwLock::new(fd_table)));
139
140 let thr = Thread::new(
141 identity.clone(),
142 tid_lease,
143 proc,
144 None,
145 starry_signal::SignalSet::default(),
146 scope,
147 )
148 .expect("failed to prepare init thread state");
149 let prepared_task = prepare_user_thread(
150 new_user_task(
151 uctx,
152 0,
153 TidNumber::try_from(pid).expect("init TID must be non-zero"),
154 ),
155 thr,
156 UserThreadOptions::new(&name).expect("failed to prepare init thread name"),
157 )
158 .expect("failed to prepare init task");
159 let staged_task = prepared_task.stage().expect("failed to stage init task");
160 let published_identity = reservation
161 .publish()
162 .expect("failed to publish init PID identity");
163 debug_assert!(Arc::ptr_eq(&published_identity, &identity));
164 staged_task.with_task(|task| task.as_thread().attach_pid_task(task));
165 tty::arm_console_irq();
166 let task = staged_task.activate();
167
168 let exit_code = task.join();
170 info!("Init process exited with code: {exit_code:?}");
171
172 let fs_context = current_fs_context();
173 let cx = fs_context.lock();
174 if let Err(err) = cx.root_dir().unmount_all() {
180 warn!("shutdown: unmount_all failed (best-effort): {err:?}");
181 }
182 cx.root_dir()
183 .filesystem()
184 .flush()
185 .expect("Failed to flush rootfs");
186}
187
188fn run_opp_calibration() {
195 info!("cpufreq: running OPP calibration sweep (governor disabled this boot)");
196 for &(cluster_idx, cpu) in &[(0usize, 0usize), (1, 4), (2, 6)] {
197 let mut affinity = ax_runtime::task::sched::CpuSet::empty(ax_runtime::hal::cpu_num());
198 let cpu_id =
199 u32::try_from(cpu).unwrap_or_else(|_| panic!("cpufreq CPU id {cpu} is out of range"));
200 assert!(
201 affinity.insert(ax_runtime::task::sched::CpuId::new(cpu_id)),
202 "cpufreq calibration CPU {cpu} is outside the runtime topology"
203 );
204 let task = kernel_thread_builder(String::from("cpufreq-cal"))
205 .affinity(affinity)
206 .spawn(move || ax_driver::cpufreq::calibrate_cluster(cluster_idx, cpu))
207 .expect("failed to spawn kernel thread");
208 let _exit_code = task.join().expect("failed to join kernel thread");
209 }
210 info!("cpufreq: OPP calibration sweep complete");
211}
212
213fn spawn_cpufreq_governor() {
226 if !ax_driver::cpufreq::governor_wanted() {
227 return;
228 }
229 info!("Initialize cpufreq ondemand governor...");
230 let _ = kernel_thread_builder(String::from("cpufreq-gov"))
231 .spawn(cpufreq_governor_loop)
232 .expect("failed to spawn kernel thread");
233}
234
235fn cpufreq_governor_loop() {
241 let period = core::time::Duration::from_millis(ax_driver::cpufreq::governor_period_ms());
242 loop {
243 sleep(period);
244 let mut busy = [0u64; 8];
247 for (cpu, slot) in busy.iter_mut().enumerate() {
248 *slot = ax_runtime::task::sched::cpu_busy_runtime_ns(
249 ax_runtime::task::sched::CpuId::new(cpu as u32),
250 )
251 .unwrap_or(0);
252 }
253 ax_driver::cpufreq::governor_poll(&busy);
254 }
255}