Skip to main content

strat9_kernel/process/scheduler/
task_ops.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23use super::{runtime_ops::finish_switch, *};
24use crate::{memory::UserSliceWrite, sync::FixedQueue};
25
26const PENDING_SILO_CLEANUPS_CAPACITY: usize = 256;
27
28static PENDING_SILO_CLEANUPS: SpinLock<FixedQueue<TaskId, PENDING_SILO_CLEANUPS_CAPACITY>> =
29    SpinLock::new(FixedQueue::new());
30
31/// Thread groups whose namespace/VFS bindings must be released at a safe
32/// point (the reap path holds the scheduler lock, where VFS access is
33/// forbidden).
34static PENDING_BINDING_CLEANUPS: SpinLock<FixedQueue<Pid, PENDING_SILO_CLEANUPS_CAPACITY>> =
35    SpinLock::new(FixedQueue::new());
36
37/// Mark the current task as Dead and yield to the scheduler.
38///
39/// Called by SYS_PROC_EXIT. The task will not be re-queued because
40/// `pick_next_task()` only re-queues tasks in `Running` state.
41/// This function does not return.
42pub fn exit_current_task(exit_code: i32) -> ! {
43    // -- clear_child_tid (POSIX pthread join) --
44    // Must happen BEFORE we drop the address space - write 0 to the TID pointer
45    // and do a futex_wake so any waiting pthread_join() can proceed.
46    if let Some(task) = current_task_clone() {
47        let tidptr = task
48            .clear_child_tid
49            .load(core::sync::atomic::Ordering::Relaxed);
50        if tidptr != 0 {
51            let zero = 0u32.to_ne_bytes();
52            // POSIX clear_child_tid targets a userspace u32; keep the existing
53            // alignment check for futex semantics, but validate the mapping via
54            // UserSliceWrite instead of dereferencing the raw userspace pointer.
55            if (tidptr & 3) == 0 {
56                if let Ok(user) = UserSliceWrite::new(tidptr, zero.len()) {
57                    user.copy_from(&zero);
58                }
59                // Futex wake: wake all threads waiting on this address (e.g. pthread_join).
60                let _ = crate::syscall::futex::sys_futex_wake(tidptr, u32::MAX);
61            }
62        }
63
64        // -- robust_list (clean up held mutexes) --
65        // Walk the robust list and mark any held futexes as FUTEX_OWNER_DIED,
66        // then wake waiters. Prevents deadlocks when a thread dies holding a mutex.
67        crate::syscall::robust_list::cleanup_robust_list(&task);
68
69        // -- user-stack canary check (issue #63) --
70        // The address space is still alive here (it dies with the Process
71        // Arc later), so the top-of-stack word can still be read.
72        task.verify_user_stack_canary();
73
74        // -- kernel-owned user stack (/thread/create) --
75        // Reclaim the user stack the kernel allocated for this thread. Done
76        // while still the running task so the address space is current on
77        // this CPU; idempotent with the cleanup_task_resources path.
78        crate::process::thread_ops::reclaim_kernel_user_stack(&task);
79
80        // -- descriptors (POSIX: closed when the last thread exits) --
81        // The fd table is shared by the whole thread group, so only the last
82        // thread may close it. Closing here (not at reap) releases pipe ends
83        // so peers waiting for EOF can proceed while we are still a zombie.
84        if crate::process::get_task_ids_in_tgid(task.tgid).len() <= 1 {
85            // SAFETY: last thread of the process; no other thread can
86            // concurrently access the shared descriptor table.
87            unsafe { (&mut *task.process.fd_table.get()).close_all() };
88
89            // -- IPC ports served by this process --
90            // Tear them down now, not when the parent finally reaps the
91            // zombie: a scheme server that exits (or panics) while its
92            // parent never calls wait() would otherwise leave its mount
93            // pointing at a live-looking port that nobody serves, and every
94            // client of that scheme (`ls /bus`, `stat /net`, ...) would block
95            // forever. Queued/pending callers get an error reply instead.
96            // Idempotent with `cleanup_task_resources` at reap time.
97            crate::ipc::port::cleanup_ports_for_task(task.id);
98
99            // -- namespace/VFS bindings owned by this thread group --
100            // Drop them now so a crashed client cannot leave an EEXIST path
101            // behind for its next incarnation. Idempotent with the reap-time
102            // cleanup below; bounded by the binding/mount table sizes.
103            crate::namespace::release_owned_by(task.tgid);
104            crate::vfs::unmount_owned_by(task.tgid);
105        }
106    }
107
108    let cpu_index = current_cpu_index();
109    let mut parent_to_signal: Option<TaskId> = None;
110    let mut ipi_to_cpu: Option<usize> = None;
111    {
112        let saved_flags = save_flags_and_cli();
113        // Lock order: GLOBAL (rank 1) -> IDENTITY write (rank 2).
114        lockdep_acquire(LockRank::Global, None);
115        let mut scheduler = GLOBAL_SCHED_STATE.lock();
116        let current = {
117            lockdep_acquire(LockRank::Local, Some(cpu_index));
118            let local = LOCAL_SCHEDULERS[cpu_index].lock();
119            let task = local.as_ref().and_then(|cpu| cpu.current_task.clone());
120            lockdep_release(LockRank::Local);
121            drop(local);
122            task
123        };
124        if let Some(ref mut sched) = *scheduler {
125            if let Some(current) = current {
126                let current_id = current.id;
127                let current_pid = current.pid;
128                let parent = {
129                    lockdep_acquire(LockRank::IdentityR, None);
130                    let identity = SCHED_IDENTITY.read();
131                    let p = identity.parent_of.get(&current_id).copied();
132                    lockdep_release(LockRank::IdentityR);
133                    drop(identity);
134                    p
135                };
136                let _ = sched.clear_task_wake_deadline_locked(current_id);
137                // Drop any per-CPU signal hint still tagged with this task so
138                // it cannot force the scheduler-lock fallback on another CPU.
139                crate::arch::percpu::clear_signal_hint_for_task(current_id.as_u64());
140                current.set_state(TaskState::Dead);
141                sched.task_cpu.remove(&current_id);
142                {
143                    lockdep_acquire(LockRank::IdentityW, None);
144                    let mut identity = SCHED_IDENTITY.write();
145                    GlobalSchedState::unregister_identity_locked(
146                        &mut identity,
147                        current_id,
148                        current_pid,
149                        current.tid,
150                    );
151                    identity.parent_of.remove(&current_id);
152                    lockdep_release(LockRank::IdentityW);
153                    drop(identity);
154                }
155
156                {
157                    lockdep_acquire(LockRank::IdentityW, None);
158                    let mut identity = SCHED_IDENTITY.write();
159                    ipi_to_cpu = reparent_children(sched, &mut identity, current_id);
160                    lockdep_release(LockRank::IdentityW);
161                    drop(identity);
162                }
163
164                if parent.is_some() {
165                    sched.zombies.insert(current_id, (exit_code, current_pid));
166                }
167                if let Some(parent_id) = parent {
168                    let (_, ipi_wake) = sched.wake_task_locked(parent_id);
169                    if ipi_to_cpu.is_none() {
170                        ipi_to_cpu = ipi_wake;
171                    }
172                    parent_to_signal = Some(parent_id);
173                }
174            }
175        }
176        lockdep_release(LockRank::Global);
177        drop(scheduler);
178        restore_flags(saved_flags);
179    }
180    if let Some(ci) = ipi_to_cpu {
181        send_resched_ipi_to_cpu(ci);
182    }
183
184    if let Some(parent_id) = parent_to_signal {
185        // Must happen outside scheduler lock to avoid lock recursion.
186        let _ =
187            crate::process::signal::send_signal(parent_id, crate::process::signal::Signal::SIGCHLD);
188    }
189
190    // Yield to pick the next task. Since we're Dead, we won't come back.
191    // Use yield_dead_task() which bypasses the PreemptGuard check : the task
192    // is already marked Dead and will never run again, so the guard is irrelevant.
193    // Using yield_task() here would silently return if a PreemptGuard is active,
194    // leaving the dead task spinning in the hlt() loop below.
195    yield_dead_task();
196
197    // Safety net - should never reach here
198    loop {
199        crate::arch::hlt();
200    }
201}
202
203/// Get the current task's ID (if any task is running).
204pub fn current_task_id() -> Option<TaskId> {
205    let saved_flags = save_flags_and_cli();
206    let cpu_index = current_cpu_index();
207    let id = LOCAL_SCHEDULERS[cpu_index]
208        .lock()
209        .as_ref()
210        .and_then(|cpu| cpu.current_task.as_ref().map(|t| t.id));
211    restore_flags(saved_flags);
212    id
213}
214
215/// Get the current task's ID without blocking (safe for exceptions).
216pub fn current_task_id_try() -> Option<TaskId> {
217    let saved_flags = save_flags_and_cli();
218    let cpu_index = current_cpu_index();
219    let id = LOCAL_SCHEDULERS[cpu_index]
220        .try_lock_no_irqsave()
221        .and_then(|guard| {
222            guard
223                .as_ref()
224                .and_then(|cpu| cpu.current_task.as_ref().map(|t| t.id))
225        });
226    restore_flags(saved_flags);
227    id
228}
229
230/// Get the current process ID (POSIX pid).
231pub fn current_pid() -> Option<Pid> {
232    current_task_clone().map(|t| t.pid)
233}
234
235/// Get the current thread ID (POSIX tid).
236pub fn current_tid() -> Option<Tid> {
237    current_task_clone().map(|t| t.tid)
238}
239
240/// Get the current process group id.
241pub fn current_pgid() -> Option<Pid> {
242    current_task_clone().map(|t| t.pgid.load(Ordering::Relaxed))
243}
244
245/// Get the current session id.
246pub fn current_sid() -> Option<Pid> {
247    current_task_clone().map(|t| t.sid.load(Ordering::Relaxed))
248}
249
250/// Get the current task (cloned Arc), if any.
251#[track_caller]
252pub fn current_task_clone() -> Option<Arc<Task>> {
253    let saved_flags = save_flags_and_cli();
254    let cpu_index = current_cpu_index();
255    let caller = core::panic::Location::caller();
256    let task = LOCAL_SCHEDULERS[cpu_index].lock().as_ref().and_then(|cpu| {
257        let arc = cpu.current_task.as_ref()?;
258        let strong = Arc::strong_count(arc);
259        // Heuristic only: strong_count can move concurrently, so this is a
260        // diagnostic signal for suspicious scheduler state, not a formal
261        // corruption proof. Keep the warning but do not mutate scheduler state.
262        if strong == 0 || strong > (isize::MAX as usize) / 2 {
263            let ptr = Arc::as_ptr(arc) as *const u8;
264            crate::serial_println!(
265                "[sched] suspicious Arc refcount (heuristic): cpu={} strong={:#x} ptr={:p} caller={}:{}",
266                cpu_index,
267                strong,
268                ptr,
269                caller.file(),
270                caller.line(),
271            );
272        }
273        Some(arc.clone())
274    });
275    restore_flags(saved_flags);
276    task
277}
278
279/// Best-effort, non-blocking variant of [`current_task_clone`].
280///
281/// Returns `None` when the scheduler lock is contended.
282/// Useful in cleanup paths where blocking on `GLOBAL_SCHED_STATE.lock()` could deadlock.
283#[track_caller]
284pub fn current_task_clone_try() -> Option<Arc<Task>> {
285    let saved_flags = save_flags_and_cli();
286    let cpu_index = current_cpu_index();
287    let caller = core::panic::Location::caller();
288    let task = LOCAL_SCHEDULERS[cpu_index]
289        .try_lock_no_irqsave()
290        .and_then(|guard| {
291            guard.as_ref().and_then(|cpu| {
292                let arc = cpu.current_task.as_ref()?;
293                let strong = Arc::strong_count(arc);
294                // Heuristic only: strong_count can move concurrently, so this is a
295                // diagnostic signal for suspicious scheduler state, not a formal
296                // corruption proof.
297                if strong == 0 || strong > (isize::MAX as usize) / 2 {
298                    let ptr = Arc::as_ptr(arc) as *const u8;
299                    crate::serial_println!(
300                        "[sched] suspicious Arc refcount (heuristic): cpu={} strong={:#x} ptr={:p} caller={}:{}",
301                        cpu_index,
302                        strong,
303                        ptr,
304                        caller.file(),
305                        caller.line(),
306                    );
307                }
308                Some(arc.clone())
309            })
310        });
311    restore_flags(saved_flags);
312    task
313}
314
315/// Debug-only blocking variant used to diagnose early ring3 entry stalls.
316///
317/// Spins with `try_lock()` so we can emit progress logs instead of blocking
318/// silently on `GLOBAL_SCHED_STATE.lock()`.
319pub fn current_task_clone_spin_debug(trace_label: &str) -> Option<Arc<Task>> {
320    let saved_flags = save_flags_and_cli();
321    let cpu_index = current_cpu_index();
322    let mut spins = 0usize;
323    let result = loop {
324        if let Some(guard) = LOCAL_SCHEDULERS[cpu_index].try_lock_no_irqsave() {
325            break guard.as_ref().and_then(|cpu| {
326                if cpu.current_task.is_none() {
327                    debug_trace_putc(b'N');
328                    return None;
329                }
330                let arc = cpu.current_task.as_ref().unwrap();
331                let strong = Arc::strong_count(arc);
332                // Racy, pifometric diagnostic only: strong_count can move
333                // concurrently, so this is a heuristic for suspicious
334                // scheduler state, not a formal corruption proof.
335                if strong == 0 || strong > (isize::MAX as usize) / 2 {
336                    let ptr = Arc::as_ptr(arc) as *const u8;
337                    crate::serial_force_println!(
338                        "[trace][sched] {} suspicious current_task heuristic cpu={} strong={:#x} ptr={:p}",
339                        trace_label,
340                        cpu_index,
341                        strong,
342                        ptr,
343                    );
344                }
345                Some(arc.clone())
346            });
347        }
348
349        spins = spins.saturating_add(1);
350        if spins == 2_000_000 {
351            crate::serial_force_println!(
352                "[trace][sched] {} waiting current_task cpu={} owner_cpu={}",
353                trace_label,
354                cpu_index,
355                GLOBAL_SCHED_STATE.owner_cpu()
356            );
357            spins = 0;
358        }
359        core::hint::spin_loop();
360    };
361    restore_flags(saved_flags);
362    result
363}
364
365/// Resolve a POSIX pid to internal TaskId.
366pub fn get_task_id_by_pid(pid: Pid) -> Option<TaskId> {
367    SCHED_IDENTITY.read().pid_to_task.get(&pid).copied()
368}
369
370/// Resolve a POSIX pid to the corresponding task.
371pub fn get_task_by_pid(pid: Pid) -> Option<Arc<Task>> {
372    let tid = get_task_id_by_pid(pid)?;
373    get_task_by_id(tid)
374}
375
376/// Resolve a direct child of `parent` by POSIX pid.
377///
378/// Unlike the global pid index, this remains valid after the child has called
379/// exit and before it is reaped, because the task object stays in `all_tasks`
380/// until waitpid consumes the zombie.
381///
382/// Lock order: `GLOBAL_SCHED_STATE` before `SCHED_IDENTITY` (see module docs).
383pub fn get_child_task_id_by_pid(parent: TaskId, pid: Pid) -> Option<TaskId> {
384    let saved_flags = save_flags_and_cli();
385    let out = {
386        let scheduler = GLOBAL_SCHED_STATE.lock();
387        if let Some(ref sched) = *scheduler {
388            let children = {
389                let identity = SCHED_IDENTITY.read();
390                identity
391                    .children_of
392                    .get(&parent)
393                    .cloned()
394                    .unwrap_or_default()
395            };
396            if children.is_empty() {
397                None
398            } else {
399                children.iter().copied().find(|child_id| {
400                    sched
401                        .all_tasks
402                        .get(child_id)
403                        .map(|task| task.pid == pid)
404                        .unwrap_or(false)
405                })
406            }
407        } else {
408            None
409        }
410    };
411    restore_flags(saved_flags);
412    out
413}
414
415/// Resolve a POSIX tid to the corresponding internal task id.
416pub fn get_task_id_by_tid(tid: Tid) -> Option<TaskId> {
417    let identity = SCHED_IDENTITY.read();
418    identity
419        .tid_to_task
420        .get(&tid)
421        .copied()
422        .or_else(|| identity.pid_to_task.get(&(tid as Pid)).copied())
423}
424
425/// Resolve a direct child of `parent` by POSIX tid.
426///
427/// This remains valid for dead-but-not-yet-reaped threads because it scans the
428/// caller's child set and the retained task object instead of relying on the
429/// global tid index removed during exit.
430///
431/// Lock order: `GLOBAL_SCHED_STATE` before `SCHED_IDENTITY` (see module docs).
432pub fn get_child_task_id_by_tid(parent: TaskId, tid: Tid) -> Option<TaskId> {
433    let saved_flags = save_flags_and_cli();
434    let out = {
435        let scheduler = GLOBAL_SCHED_STATE.lock();
436        if let Some(ref sched) = *scheduler {
437            let children = {
438                let identity = SCHED_IDENTITY.read();
439                identity
440                    .children_of
441                    .get(&parent)
442                    .cloned()
443                    .unwrap_or_default()
444            };
445            if children.is_empty() {
446                None
447            } else {
448                children.iter().copied().find(|child_id| {
449                    sched
450                        .all_tasks
451                        .get(child_id)
452                        .map(|task| task.tid == tid)
453                        .unwrap_or(false)
454                })
455            }
456        } else {
457            None
458        }
459    };
460    restore_flags(saved_flags);
461    out
462}
463
464/// Resolve a PID to the current process group id.
465pub fn get_pgid_by_pid(pid: Pid) -> Option<Pid> {
466    SCHED_IDENTITY.read().pid_to_pgid.get(&pid).copied()
467}
468
469/// Resolve a PID to the current session id.
470pub fn get_sid_by_pid(pid: Pid) -> Option<Pid> {
471    SCHED_IDENTITY.read().pid_to_sid.get(&pid).copied()
472}
473
474/// Collect task IDs that currently belong to process group `pgid`.
475pub fn get_task_ids_in_pgid(pgid: Pid) -> alloc::vec::Vec<TaskId> {
476    use alloc::vec::Vec;
477    SCHED_IDENTITY
478        .read()
479        .pgid_members
480        .get(&pgid)
481        .cloned()
482        .unwrap_or_else(Vec::new)
483}
484
485/// Collect task IDs that currently belong to thread group `tgid`.
486pub fn get_task_ids_in_tgid(tgid: Pid) -> alloc::vec::Vec<TaskId> {
487    use alloc::vec::Vec;
488    let saved_flags = save_flags_and_cli();
489    let out = {
490        let scheduler = GLOBAL_SCHED_STATE.lock();
491        if let Some(ref sched) = *scheduler {
492            sched
493                .all_tasks
494                .values()
495                .filter(|task| task.tgid == tgid)
496                .map(|task| task.id)
497                .collect::<Vec<_>>()
498        } else {
499            Vec::new()
500        }
501    };
502    restore_flags(saved_flags);
503    out
504}
505
506/// True when at least one task of thread group `tgid` is still tracked.
507///
508/// Dead-owner detection for namespace bindings: a reaped tgid owns nothing.
509pub fn tgid_is_alive(tgid: Pid) -> bool {
510    let saved_flags = save_flags_and_cli();
511    let alive = GLOBAL_SCHED_STATE
512        .lock()
513        .as_ref()
514        .is_some_and(|sched| sched.all_tasks.values().any(|task| task.tgid == tgid));
515    restore_flags(saved_flags);
516    alive
517}
518
519/// Set process group id for `target_pid` (or current if `None`).
520pub fn set_process_group(
521    requester: TaskId,
522    target_pid: Option<Pid>,
523    new_pgid: Option<Pid>,
524) -> Result<Pid, crate::syscall::error::SyscallError> {
525    use crate::syscall::error::SyscallError;
526
527    let saved_flags = save_flags_and_cli();
528    let result = (|| -> Result<Pid, SyscallError> {
529        let scheduler = GLOBAL_SCHED_STATE.lock();
530        let sched = scheduler.as_ref().ok_or(SyscallError::Fault)?;
531
532        let requester_task = sched
533            .all_tasks
534            .get(&requester)
535            .cloned()
536            .ok_or(SyscallError::Fault)?;
537        let requester_sid = requester_task.sid.load(Ordering::Relaxed);
538
539        let target_id = match target_pid {
540            None => requester,
541            Some(pid) => SCHED_IDENTITY
542                .read()
543                .pid_to_task
544                .get(&pid)
545                .copied()
546                .ok_or(SyscallError::NotFound)?,
547        };
548
549        if target_id != requester {
550            let is_child = SCHED_IDENTITY
551                .read()
552                .children_of
553                .get(&requester)
554                .map(|children| children.iter().any(|child| *child == target_id))
555                .unwrap_or(false);
556            if !is_child {
557                return Err(SyscallError::PermissionDenied);
558            }
559        }
560
561        let target_task = sched
562            .all_tasks
563            .get(&target_id)
564            .cloned()
565            .ok_or(SyscallError::NotFound)?;
566        let target_pid_value = target_task.pid;
567        let target_sid = target_task.sid.load(Ordering::Relaxed);
568
569        if target_sid != requester_sid {
570            return Err(SyscallError::PermissionDenied);
571        }
572
573        if target_pid_value == target_sid {
574            return Err(SyscallError::PermissionDenied);
575        }
576
577        let desired_pgid = new_pgid.unwrap_or(target_pid_value);
578        if desired_pgid != target_pid_value {
579            let group_leader_tid = SCHED_IDENTITY
580                .read()
581                .pid_to_task
582                .get(&desired_pgid)
583                .copied()
584                .ok_or(SyscallError::NotFound)?;
585            let group_leader = sched
586                .all_tasks
587                .get(&group_leader_tid)
588                .ok_or(SyscallError::NotFound)?;
589            if group_leader.sid.load(Ordering::Relaxed) != target_sid {
590                return Err(SyscallError::PermissionDenied);
591            }
592        }
593
594        // Mutate identity maps under SCHED_IDENTITY lock while still holding GLOBAL_SCHED_STATE.
595        let old_pgid = target_task.pgid.load(Ordering::Relaxed);
596        let actual_new_pgid = new_pgid.unwrap_or(target_task.pid);
597        target_task.pgid.store(actual_new_pgid, Ordering::Relaxed);
598        {
599            let mut identity = SCHED_IDENTITY.write();
600            GlobalSchedState::member_remove(&mut identity.pgid_members, old_pgid, target_id);
601            GlobalSchedState::member_add(&mut identity.pgid_members, actual_new_pgid, target_id);
602            identity
603                .pid_to_pgid
604                .insert(target_task.pid, actual_new_pgid);
605        }
606        Ok(actual_new_pgid)
607    })();
608    restore_flags(saved_flags);
609    result
610}
611
612/// Create a new session for the calling task.
613pub fn create_session(requester: TaskId) -> Result<Pid, crate::syscall::error::SyscallError> {
614    use crate::syscall::error::SyscallError;
615
616    let saved_flags = save_flags_and_cli();
617    let result = (|| -> Result<Pid, SyscallError> {
618        let scheduler = GLOBAL_SCHED_STATE.lock();
619        let sched = scheduler.as_ref().ok_or(SyscallError::Fault)?;
620        let requester_task = sched
621            .all_tasks
622            .get(&requester)
623            .cloned()
624            .ok_or(SyscallError::Fault)?;
625
626        let pid = requester_task.pid;
627        if requester_task.pgid.load(Ordering::Relaxed) == pid {
628            return Err(SyscallError::PermissionDenied);
629        }
630
631        let old_sid = requester_task.sid.load(Ordering::Relaxed);
632        let old_pgid = requester_task.pgid.load(Ordering::Relaxed);
633        requester_task.sid.store(pid, Ordering::Relaxed);
634        requester_task.pgid.store(pid, Ordering::Relaxed);
635        {
636            let mut identity = SCHED_IDENTITY.write();
637            GlobalSchedState::member_remove(&mut identity.sid_members, old_sid, requester);
638            GlobalSchedState::member_remove(&mut identity.pgid_members, old_pgid, requester);
639            GlobalSchedState::member_add(&mut identity.sid_members, pid, requester);
640            GlobalSchedState::member_add(&mut identity.pgid_members, pid, requester);
641            identity.pid_to_sid.insert(pid, pid);
642            identity.pid_to_pgid.insert(pid, pid);
643        }
644        Ok(pid)
645    })();
646    restore_flags(saved_flags);
647    result
648}
649
650/// Get a task by its TaskId (if still registered).
651pub fn get_task_by_id(id: TaskId) -> Option<Arc<Task>> {
652    let saved_flags = save_flags_and_cli();
653    let task = {
654        let scheduler = GLOBAL_SCHED_STATE.lock();
655        if let Some(ref sched) = *scheduler {
656            sched.all_tasks.get(&id).cloned()
657        } else {
658            None
659        }
660    };
661    restore_flags(saved_flags);
662    task
663}
664
665/// Update a task scheduling policy and requeue if needed.
666pub fn set_task_sched_policy(id: TaskId, policy: crate::process::sched::SchedPolicy) -> bool {
667    let saved_flags = save_flags_and_cli();
668    let mut ipi_to_cpu: Option<usize> = None;
669    let updated = {
670        let mut scheduler = GLOBAL_SCHED_STATE.lock();
671        if let Some(ref mut sched) = *scheduler {
672            let cpu_index = sched.task_cpu.get(&id).copied().unwrap_or(0);
673            let task = match sched.all_tasks.get(&id).cloned() {
674                Some(t) => t,
675                None => {
676                    // Restore the interrupt state before bailing out: an early
677                    // return through the lock guard alone would leave IRQs
678                    // disabled on this CPU.
679                    drop(scheduler);
680                    restore_flags(saved_flags);
681                    return false;
682                }
683            };
684            task.set_sched_policy(policy);
685            let class = sched.class_table.class_for_task(&task);
686
687            if let Some(ref mut local_cpu) = *LOCAL_SCHEDULERS[cpu_index].lock() {
688                // If task is queued in ready classes, migrate it to the new class.
689                if local_cpu.class_rqs.remove(id) {
690                    local_cpu.class_rqs.enqueue(class, task.clone());
691                }
692                local_cpu.need_resched = true;
693            }
694            if cpu_index != current_cpu_index() {
695                ipi_to_cpu = Some(cpu_index);
696            }
697            sched_trace(format_args!(
698                "set_policy task={} cpu={} policy={:?}",
699                id.as_u64(),
700                cpu_index,
701                policy
702            ));
703            true
704        } else {
705            false
706        }
707    };
708    if let Some(ci) = ipi_to_cpu {
709        send_resched_ipi_to_cpu(ci);
710    }
711    restore_flags(saved_flags);
712    updated
713}
714
715/// Get parent task ID for a child task.
716pub fn get_parent_id(child: TaskId) -> Option<TaskId> {
717    SCHED_IDENTITY.read().parent_of.get(&child).copied()
718}
719
720/// Get parent process ID for a child task.
721pub fn get_parent_pid(child: TaskId) -> Option<Pid> {
722    let parent_tid = get_parent_id(child)?;
723    let parent = get_task_by_id(parent_tid)?;
724    Some(parent.pid)
725}
726
727/// Try to reap a zombie child.
728///
729/// `target=None` means "any child".
730pub fn try_wait_child(parent: TaskId, target: Option<TaskId>) -> WaitChildResult {
731    let saved_flags = save_flags_and_cli();
732    let result = {
733        let mut scheduler = GLOBAL_SCHED_STATE.lock();
734        if let Some(ref mut sched) = *scheduler {
735            sched.try_reap_child_locked(parent, target)
736        } else {
737            WaitChildResult::NoChildren
738        }
739    };
740    restore_flags(saved_flags);
741    result
742}
743
744/// Block the current task and yield to the scheduler.
745///
746/// The current task is moved from Running to Blocked state and placed
747/// in the `blocked_tasks` map. It will not be re-scheduled until
748/// `wake_task(id)` is called.
749///
750/// ## Lock design
751///
752/// This function acquires **only** the `BLOCKED_TASKS` lock + the current
753/// CPU's `LOCAL_SCHEDULERS[cpu]` lock. It does **not** touch
754/// `GLOBAL_SCHED_STATE`, avoiding contention with cold-path operations
755/// (fork, exit, kill).
756///
757/// ## Lost-wakeup prevention
758///
759/// Before actually blocking, this function checks the task's `wake_pending`
760/// flag. If a concurrent `wake_task()` fired between the moment the task
761/// added itself to a `WaitQueue` and this call, the flag will be set and
762/// the function returns immediately without blocking.
763///
764/// Must NOT be called with interrupts disabled or while holding the
765/// scheduler lock (this function acquires both).
766pub fn block_current_task() {
767    let saved_flags = save_flags_and_cli();
768    let cpu_index = current_cpu_index();
769
770    let switch_target = {
771        // Lock order: BLOCKED (rank 3) -> LOCAL (rank 4).
772        lockdep_acquire(LockRank::Blocked, None);
773        let mut blocked = super::BLOCKED_TASKS.lock();
774        lockdep_acquire(LockRank::Local, Some(cpu_index));
775        let mut local = LOCAL_SCHEDULERS[cpu_index].lock();
776        let out = if let Some(ref mut cpu) = *local {
777            if let Some(ref current) = cpu.current_task {
778                if current
779                    .wake_pending
780                    .swap(false, core::sync::atomic::Ordering::AcqRel)
781                {
782                    // Pending wakeup consumed - do not block.
783                    None
784                } else {
785                    current.set_state(TaskState::Blocked);
786                    current.begin_block();
787                    if crate::trace::enabled(crate::trace::category::SCHED_BLOCK) {
788                        crate::trace::record(
789                            crate::trace::category::SCHED_BLOCK,
790                            crate::trace::TraceKind::SchedBlock,
791                            0,
792                            crate::trace::TraceTaskCtx::from_task(current.as_ref()),
793                            0,
794                            0,
795                            current.id.as_u64(),
796                            0,
797                        );
798                    }
799                    // Record home CPU so wake_task can route without GLOBAL.
800                    current
801                        .home_cpu
802                        .store(cpu_index, core::sync::atomic::Ordering::Relaxed);
803                    blocked.insert(current.id, current.clone());
804                    super::core_impl::yield_cpu_local(cpu, cpu_index)
805                }
806            } else {
807                None
808            }
809        } else {
810            None
811        };
812        lockdep_release(LockRank::Local);
813        drop(local);
814        lockdep_release(LockRank::Blocked);
815        drop(blocked);
816        out
817    }; // Locks released
818
819    if let Some(ref target) = switch_target {
820        // SAFETY: no scheduler locks held, no allocation, no IPI.
821        unsafe {
822            crate::process::task::do_switch_context(target);
823        }
824        finish_switch();
825    }
826
827    restore_flags(saved_flags);
828}
829
830/// Wake a blocked task by its ID.
831///
832/// Moves the task from `blocked_tasks` to the ready queue and sets its
833/// state to Ready. Returns `true` if the task was found and woken.
834///
835/// ## Lock design
836///
837/// The primary path (task found in `BLOCKED_TASKS`) acquires **only** the
838/// `BLOCKED_TASKS` lock + the target CPU's `LOCAL_SCHEDULERS[cpu]` lock.
839/// It does **not** touch `GLOBAL_SCHED_STATE`, avoiding contention with
840/// cold-path operations (fork, exit, kill).
841///
842/// ## Lost-wakeup prevention
843///
844/// If the task is not yet in `blocked_tasks` (it is still transitioning
845/// from Ready -> Blocked inside `block_current_task()`), this function sets
846/// the task's `wake_pending` flag so that `block_current_task()` will see
847/// the pending wakeup and return immediately without actually blocking.
848pub fn wake_task(id: TaskId) -> bool {
849    wake_task_with(id, false)
850}
851
852/// Like [`wake_task`], but place the woken task on the **calling** CPU when
853/// its affinity allows it (directed wakeup).
854///
855/// Used by the IPC v2 call fast path (N3, spec §10): the server is enqueued
856/// on the caller's CPU, without an IPI, and runs as soon as the caller
857/// blocks waiting for the reply; the reply wakes the caller back the same
858/// way. This is a placement hint, not a scheduling-context donation: the
859/// local scheduler class still decides when the woken task runs.
860pub fn wake_task_here(id: TaskId) -> bool {
861    wake_task_with(id, true)
862}
863
864fn wake_task_with(id: TaskId, here: bool) -> bool {
865    let saved_flags = save_flags_and_cli();
866
867    // --- Primary path: task is in BLOCKED_TASKS ---
868    // Lock order: BLOCKED (rank 3) -> LOCAL (rank 4).
869    let mut ipi_cpu: Option<usize> = None;
870    let mut woken = false;
871
872    {
873        lockdep_acquire(LockRank::Blocked, None);
874        let mut blocked = super::BLOCKED_TASKS.lock();
875        if let Some(task) = blocked.remove(&id) {
876            task.end_block();
877            if crate::trace::enabled(crate::trace::category::SCHED_WAKE) {
878                crate::trace::record(
879                    crate::trace::category::SCHED_WAKE,
880                    crate::trace::TraceKind::SchedWake,
881                    0,
882                    crate::trace::TraceTaskCtx::from_task(task.as_ref()),
883                    0,
884                    0,
885                    task.id.as_u64(),
886                    0,
887                );
888            }
889            task.set_state(TaskState::Ready);
890
891            // --- CPU placement: directed (this CPU), else last_cpu, then home_cpu ---
892            let last = task.last_cpu.load(core::sync::atomic::Ordering::Relaxed);
893            let home = task.home_cpu.load(core::sync::atomic::Ordering::Relaxed);
894            let here_cpu = current_cpu_index();
895            let affinity = task
896                .affinity_mask
897                .load(core::sync::atomic::Ordering::Relaxed);
898            let here_allowed =
899                affinity == 0 || (here_cpu < 64 && affinity & (1u64 << here_cpu) != 0);
900            let cpu_index = if here && here_allowed {
901                here_cpu
902            } else {
903                super::placement_cpu(last, home)
904            };
905
906            lockdep_acquire(LockRank::Local, Some(cpu_index));
907            if let Some(ref mut local_cpu) = *LOCAL_SCHEDULERS[cpu_index].lock() {
908                let class = local_cpu.class_table.class_for_task(&task);
909                local_cpu.class_rqs.enqueue(class, task.clone());
910                local_cpu.need_resched = true;
911            }
912            lockdep_release(LockRank::Local);
913
914            ipi_cpu = if cpu_index != current_cpu_index() {
915                Some(cpu_index)
916            } else {
917                None
918            };
919            woken = true;
920        }
921        lockdep_release(LockRank::Blocked);
922        drop(blocked);
923    } // BLOCKED_TASKS lock released
924
925    if woken {
926        if let Some(ci) = ipi_cpu {
927            send_resched_ipi_to_cpu(ci);
928        }
929        restore_flags(saved_flags);
930        return true;
931    }
932
933    // === Fallback path: task not yet in BLOCKED_TASKS =================================
934    // Lock order: GLOBAL (rank 1) -> BLOCKED (rank 3) -> LOCAL (rank 4).
935    {
936        lockdep_acquire(LockRank::Global, None);
937        let mut scheduler = GLOBAL_SCHED_STATE.lock();
938        if let Some(ref mut sched) = *scheduler {
939            let (fallback_woken, fallback_ipi) = sched.wake_task_locked(id);
940            woken = fallback_woken;
941            if ipi_cpu.is_none() {
942                ipi_cpu = fallback_ipi;
943            }
944        }
945        lockdep_release(LockRank::Global);
946    }
947
948    if let Some(ci) = ipi_cpu {
949        send_resched_ipi_to_cpu(ci);
950    }
951    restore_flags(saved_flags);
952    woken
953}
954
955/// Sets task wake deadline.
956pub fn set_task_wake_deadline(id: TaskId, deadline_ns: u64) -> bool {
957    let saved_flags = save_flags_and_cli();
958    let out = {
959        let mut scheduler = GLOBAL_SCHED_STATE.lock();
960        if let Some(ref mut sched) = *scheduler {
961            sched.set_task_wake_deadline_locked(id, deadline_ns)
962        } else {
963            false
964        }
965    };
966    restore_flags(saved_flags);
967    out
968}
969
970/// Performs the clear task wake deadline operation.
971pub fn clear_task_wake_deadline(id: TaskId) -> bool {
972    set_task_wake_deadline(id, 0)
973}
974
975/// Suspend a task by ID (best-effort).
976///
977/// Moves the task to the blocked map and marks it Blocked.
978/// - If the task is the *current* task on *this* CPU, a context switch is
979///   performed immediately.
980/// - If the task is the *current* task on *another* CPU, an IPI is sent to
981///   trigger preemption on that CPU. The task will not be re-queued at the
982///   next tick because its state is Blocked.
983///
984/// ## Lock order
985///
986/// Canonical: BLOCKED (rank 3) → LOCAL (rank 4).
987/// First path (current task): re-acquires LOCAL only for yield_cpu_local,
988/// after BLOCKED has been released.
989/// Ready-queue path: acquires LOCAL to remove, releases it, then acquires
990/// BLOCKED to insert : this is safe because LOCAL is fully released before
991/// BLOCKED is acquired (no nesting).
992pub fn suspend_task(id: TaskId) -> bool {
993    let saved_flags = save_flags_and_cli();
994
995    let mut switch_target: Option<SwitchTarget> = None;
996    let mut suspended = false;
997    let mut ipi_to_cpu: Option<usize> = None;
998
999    let my_cpu = current_cpu_index();
1000
1001    // Path 1: Check if the task is the current task on any CPU.
1002    // Lock order: LOCAL (state transition) → release → BLOCKED → LOCAL (yield).
1003    // The state change happens *while* LOCAL is held and re-reads `current_task`
1004    // under the guard, so a concurrent switch on that CPU (which also takes
1005    // LOCAL) observes `Blocked` and moves the task to `task_to_drop` rather
1006    // than re-queueing it. BLOCKED is only taken after LOCAL is released.
1007    for ci in 0..crate::arch::percpu::MAX_CPUS {
1008        if !super::cpu_is_online(ci) {
1009            continue;
1010        }
1011        lockdep_acquire(LockRank::Local, Some(ci));
1012        let running = LOCAL_SCHEDULERS[ci].lock().as_ref().and_then(|cpu| {
1013            cpu.current_task.as_ref().and_then(|t| {
1014                if t.id == id {
1015                    t.set_state(TaskState::Blocked);
1016                    Some(t.clone())
1017                } else {
1018                    None
1019                }
1020            })
1021        });
1022        lockdep_release(LockRank::Local);
1023        if let Some(current) = running {
1024            current
1025                .home_cpu
1026                .store(ci, core::sync::atomic::Ordering::Relaxed);
1027            // Insert into BLOCKED_TASKS (rank 3).
1028            lockdep_acquire(LockRank::Blocked, None);
1029            super::BLOCKED_TASKS
1030                .lock()
1031                .insert(current.id, current.clone());
1032            lockdep_release(LockRank::Blocked);
1033            suspended = true;
1034            if ci == my_cpu {
1035                // Re-acquire LOCAL (rank 4) to yield. Safe because IRQs
1036                // are disabled and BLOCKED is released.
1037                lockdep_acquire(LockRank::Local, Some(ci));
1038                let mut local = LOCAL_SCHEDULERS[ci].lock();
1039                if let Some(ref mut cpu) = *local {
1040                    switch_target = super::core_impl::yield_cpu_local(cpu, ci);
1041                }
1042                lockdep_release(LockRank::Local);
1043            } else {
1044                ipi_to_cpu = Some(ci);
1045            }
1046            break;
1047        }
1048    }
1049
1050    // Path 2: Remove from ready queues (task was not running anywhere).
1051    // Lock order: LOCAL (remove from queue) → release → BLOCKED (insert).
1052    // No nesting: LOCAL is fully released before BLOCKED is acquired.
1053    if !suspended {
1054        for ci in 0..crate::arch::percpu::MAX_CPUS {
1055            if !super::cpu_is_online(ci) {
1056                continue;
1057            }
1058            lockdep_acquire(LockRank::Local, Some(ci));
1059            let removed = {
1060                let mut local = LOCAL_SCHEDULERS[ci].lock();
1061                if let Some(ref mut cpu) = *local {
1062                    cpu.class_rqs.remove(id)
1063                } else {
1064                    false
1065                }
1066            };
1067            lockdep_release(LockRank::Local);
1068            if removed {
1069                if let Some(task) = get_task_by_id(id) {
1070                    task.set_state(TaskState::Blocked);
1071                    task.home_cpu
1072                        .store(ci, core::sync::atomic::Ordering::Relaxed);
1073                    lockdep_acquire(LockRank::Blocked, None);
1074                    task.begin_block();
1075                    super::BLOCKED_TASKS.lock().insert(task.id, task.clone());
1076                    lockdep_release(LockRank::Blocked);
1077                }
1078                suspended = true;
1079                break;
1080            }
1081        }
1082    }
1083
1084    // Already blocked.
1085    if !suspended {
1086        lockdep_acquire(LockRank::Blocked, None);
1087        if super::BLOCKED_TASKS.lock().contains_key(&id) {
1088            suspended = true;
1089        }
1090        lockdep_release(LockRank::Blocked);
1091    }
1092
1093    if let Some(ref target) = switch_target {
1094        unsafe {
1095            crate::process::task::do_switch_context(target);
1096        }
1097        finish_switch();
1098    }
1099
1100    if let Some(ci) = ipi_to_cpu {
1101        send_resched_ipi_to_cpu(ci);
1102    }
1103
1104    restore_flags(saved_flags);
1105    suspended
1106}
1107
1108/// Resume a previously suspended task by ID.
1109///
1110/// Moves the task from blocked to ready queue and marks it Ready.
1111///
1112/// ## Lock order
1113///
1114/// BLOCKED (rank 3) → release → LOCAL (rank 4).  No nesting:
1115/// BLOCKED is fully released before LOCAL is acquired.
1116pub fn resume_task(id: TaskId) -> bool {
1117    let saved_flags = save_flags_and_cli();
1118    let mut ipi_to_cpu: Option<usize> = None;
1119
1120    let mut task_to_enqueue: Option<Arc<Task>> = None;
1121    {
1122        // Lock order: BLOCKED (rank 3).
1123        lockdep_acquire(LockRank::Blocked, None);
1124        let mut blocked = super::BLOCKED_TASKS.lock();
1125        if let Some(task) = blocked.remove(&id) {
1126            task.end_block();
1127            if crate::trace::enabled(crate::trace::category::SCHED_WAKE) {
1128                crate::trace::record(
1129                    crate::trace::category::SCHED_WAKE,
1130                    crate::trace::TraceKind::SchedWake,
1131                    0,
1132                    crate::trace::TraceTaskCtx::from_task(task.as_ref()),
1133                    0,
1134                    0,
1135                    task.id.as_u64(),
1136                    0,
1137                );
1138            }
1139            task.set_state(TaskState::Ready);
1140
1141            // --- CPU placement: prefer last_cpu, then home_cpu ---
1142            let last = task.last_cpu.load(core::sync::atomic::Ordering::Relaxed);
1143            let home = task.home_cpu.load(core::sync::atomic::Ordering::Relaxed);
1144            let cpu_index = super::placement_cpu(last, home);
1145
1146            // Release BLOCKED before acquiring LOCAL.
1147            lockdep_release(LockRank::Blocked);
1148            drop(blocked);
1149
1150            // Lock order: LOCAL (rank 4).
1151            lockdep_acquire(LockRank::Local, Some(cpu_index));
1152            if let Some(ref mut local_cpu) = *LOCAL_SCHEDULERS[cpu_index].lock() {
1153                let class = local_cpu.class_table.class_for_task(&task);
1154                local_cpu.class_rqs.enqueue(class, task.clone());
1155                local_cpu.need_resched = true;
1156            }
1157            lockdep_release(LockRank::Local);
1158
1159            if cpu_index != current_cpu_index() {
1160                ipi_to_cpu = Some(cpu_index);
1161            }
1162            task_to_enqueue = Some(task);
1163        } else {
1164            lockdep_release(LockRank::Blocked);
1165            drop(blocked);
1166        }
1167    }
1168
1169    if let Some(ci) = ipi_to_cpu {
1170        send_resched_ipi_to_cpu(ci);
1171    }
1172    restore_flags(saved_flags);
1173    task_to_enqueue.is_some()
1174}
1175
1176/// Kill a task by ID (best-effort).
1177///
1178/// - Ready / blocked tasks are removed and marked Dead immediately.
1179/// - If the task is the *current* task on *this* CPU, a context switch is
1180///   performed immediately.
1181/// - If the task is the *current* task on *another* CPU, an IPI triggers
1182///   preemption on that CPU; the task will not be re-queued because its
1183///   state is Dead.
1184///
1185/// Returns `true` if the task was found and killed.
1186pub fn kill_task(id: TaskId) -> bool {
1187    let pid = crate::process::get_task_by_id(id)
1188        .map(|t| t.pid)
1189        .unwrap_or(0);
1190    crate::audit::log(
1191        crate::audit::AuditCategory::Process,
1192        pid,
1193        crate::silo::task_silo_id(id).unwrap_or(0),
1194        alloc::format!("kill_task tid={}", id.as_u64()),
1195    );
1196    let saved_flags = save_flags_and_cli();
1197
1198    let mut switch_target: Option<SwitchTarget> = None;
1199    let mut killed = false;
1200    let mut ipi_to_cpu: Option<usize> = None;
1201    let mut parent_to_signal: Option<TaskId> = None;
1202
1203    {
1204        lockdep_acquire(LockRank::Global, None);
1205        let mut scheduler = GLOBAL_SCHED_STATE.lock();
1206        if let Some(ref mut sched) = *scheduler {
1207            const FORCED_KILL_EXIT_CODE: i32 = 1;
1208            let my_cpu = current_cpu_index();
1209
1210            // Check if the task is the current task on any CPU.
1211            // The Dead transition is performed *while* that CPU's LOCAL lock is
1212            // held and `current_task` is re-read under the guard, so a
1213            // concurrent switch on the target observes Dead and drops the task
1214            // instead of requeueing it.
1215            let mut running_hit: Option<(usize, Arc<Task>)> = None;
1216            for ci in 0..crate::arch::percpu::MAX_CPUS {
1217                if !super::cpu_is_online(ci) {
1218                    continue;
1219                }
1220                lockdep_acquire(LockRank::Local, Some(ci));
1221                let hit = LOCAL_SCHEDULERS[ci].lock().as_ref().and_then(|cpu| {
1222                    cpu.current_task.as_ref().and_then(|t| {
1223                        if t.id != id {
1224                            return None;
1225                        }
1226                        if t.get_state() == TaskState::Dead {
1227                            return Some(None);
1228                        }
1229                        t.set_state(TaskState::Dead);
1230                        Some(Some(t.clone()))
1231                    })
1232                });
1233                lockdep_release(LockRank::Local);
1234                match hit {
1235                    Some(Some(current)) => {
1236                        running_hit = Some((ci, current));
1237                        break;
1238                    }
1239                    // Found as current but already Dead: stop scanning.
1240                    Some(None) => break,
1241                    None => {}
1242                }
1243            }
1244            if let Some((ci, current)) = running_hit {
1245                let task_pid = current.pid;
1246                let _ = sched.clear_task_wake_deadline_locked(id);
1247                crate::arch::percpu::clear_signal_hint_for_task(id.as_u64());
1248                sched.task_cpu.remove(&id);
1249                // Single identity write: unregister + reparent + remove parent.
1250                {
1251                    lockdep_acquire(LockRank::IdentityW, None);
1252                    let mut identity = SCHED_IDENTITY.write();
1253                    GlobalSchedState::unregister_identity_locked(
1254                        &mut identity,
1255                        id,
1256                        task_pid,
1257                        current.tid,
1258                    );
1259                    identity.parent_of.remove(&current.id);
1260                    lockdep_release(LockRank::IdentityW);
1261                    drop(identity);
1262                }
1263                // reparent_children needs a separate identity write since it
1264                // also needs sched.zombies check : but we can merge if we
1265                // pass a pre-built identity. For now keep separate.
1266                let (parent, ipi_death) = {
1267                    lockdep_acquire(LockRank::IdentityW, None);
1268                    let mut identity = SCHED_IDENTITY.write();
1269                    let result = reparent_children(sched, &mut identity, id);
1270                    // re-check parent after reparent may have removed it
1271                    let parent = identity.parent_of.get(&id).copied();
1272                    lockdep_release(LockRank::IdentityW);
1273                    drop(identity);
1274                    if let Some(parent_id) = parent {
1275                        sched.zombies.insert(id, (FORCED_KILL_EXIT_CODE, task_pid));
1276                        let (_, ipi_wake) = sched.wake_task_locked(parent_id);
1277                        (Some(parent_id), result.or(ipi_wake))
1278                    } else {
1279                        // Parent was not in identity, but might still need zombie entry
1280                        // if the task had a parent. Use reparent result as signal.
1281                        (None, result)
1282                    }
1283                };
1284                parent_to_signal = parent;
1285                killed = true;
1286                if ci == my_cpu {
1287                    lockdep_acquire(LockRank::Local, Some(ci));
1288                    let mut local = LOCAL_SCHEDULERS[ci].lock();
1289                    if let Some(ref mut cpu) = *local {
1290                        switch_target = super::core_impl::yield_cpu_local(cpu, ci);
1291                    }
1292                    lockdep_release(LockRank::Local);
1293                    drop(local);
1294                } else {
1295                    ipi_to_cpu = Some(ci);
1296                }
1297                if ipi_to_cpu.is_none() {
1298                    ipi_to_cpu = ipi_death;
1299                }
1300            }
1301
1302            // Remove from ready queues.
1303            if !killed {
1304                let mut removed_from_ready = false;
1305                for ci in 0..crate::arch::percpu::MAX_CPUS {
1306                    if !super::cpu_is_online(ci) {
1307                        continue;
1308                    }
1309                    lockdep_acquire(LockRank::Local, Some(ci));
1310                    let removed = {
1311                        let mut local = LOCAL_SCHEDULERS[ci].lock();
1312                        if let Some(ref mut cpu) = *local {
1313                            cpu.class_rqs.remove(id)
1314                        } else {
1315                            false
1316                        }
1317                    };
1318                    lockdep_release(LockRank::Local);
1319                    if removed {
1320                        removed_from_ready = true;
1321                        break;
1322                    }
1323                }
1324                if removed_from_ready {
1325                    let _ = sched.clear_task_wake_deadline_locked(id);
1326                    if let Some(task) = sched.remove_all_task_locked(id) {
1327                        let task_pid = task.pid;
1328                        crate::arch::percpu::clear_signal_hint_for_task(id.as_u64());
1329                        task.set_state(TaskState::Dead);
1330                        cleanup_task_resources(&task);
1331                        sched.task_cpu.remove(&id);
1332                        {
1333                            lockdep_acquire(LockRank::IdentityW, None);
1334                            let mut identity = SCHED_IDENTITY.write();
1335                            GlobalSchedState::unregister_identity_locked(
1336                                &mut identity,
1337                                id,
1338                                task_pid,
1339                                task.tid,
1340                            );
1341                            lockdep_release(LockRank::IdentityW);
1342                            drop(identity);
1343                        }
1344                        let (parent, ipi_death) =
1345                            finalize_forced_death(sched, id, FORCED_KILL_EXIT_CODE, task_pid);
1346                        parent_to_signal = parent;
1347                        if ipi_to_cpu.is_none() {
1348                            ipi_to_cpu = ipi_death;
1349                        }
1350                    }
1351                    killed = true;
1352                }
1353            }
1354
1355            // Remove from blocked map.
1356            if !killed {
1357                lockdep_acquire(LockRank::Blocked, None);
1358                if let Some(task) = super::BLOCKED_TASKS.lock().remove(&id) {
1359                    task.end_block();
1360                    lockdep_release(LockRank::Blocked);
1361                    let task_pid = task.pid;
1362                    let _ = sched.clear_task_wake_deadline_locked(id);
1363                    crate::arch::percpu::clear_signal_hint_for_task(id.as_u64());
1364                    task.set_state(TaskState::Dead);
1365                    cleanup_task_resources(&task);
1366                    let _ = sched.remove_all_task_locked(id);
1367                    sched.task_cpu.remove(&id);
1368                    {
1369                        lockdep_acquire(LockRank::IdentityW, None);
1370                        let mut identity = SCHED_IDENTITY.write();
1371                        GlobalSchedState::unregister_identity_locked(
1372                            &mut identity,
1373                            id,
1374                            task_pid,
1375                            task.tid,
1376                        );
1377                        lockdep_release(LockRank::IdentityW);
1378                        drop(identity);
1379                    }
1380                    let (parent, ipi_death) =
1381                        finalize_forced_death(sched, id, FORCED_KILL_EXIT_CODE, task_pid);
1382                    parent_to_signal = parent;
1383                    if ipi_to_cpu.is_none() {
1384                        ipi_to_cpu = ipi_death;
1385                    }
1386                    killed = true;
1387                } else {
1388                    lockdep_release(LockRank::Blocked);
1389                }
1390            }
1391        }
1392        lockdep_release(LockRank::Global);
1393    } // scheduler lock released before IPI and context switch
1394
1395    if let Some(ref target) = switch_target {
1396        unsafe {
1397            crate::process::task::do_switch_context(target);
1398        }
1399        finish_switch();
1400    }
1401
1402    if let Some(ci) = ipi_to_cpu {
1403        send_resched_ipi_to_cpu(ci);
1404    }
1405
1406    if let Some(parent_id) = parent_to_signal {
1407        // Must happen outside scheduler lock to avoid lock recursion.
1408        let _ =
1409            crate::process::signal::send_signal(parent_id, crate::process::signal::Signal::SIGCHLD);
1410    }
1411
1412    restore_flags(saved_flags);
1413    killed
1414}
1415
1416/// Performs the finalize forced death operation.
1417///
1418/// Lock order: caller holds GLOBAL_SCHED_STATE (rank 1).
1419/// This function acquires SCHED_IDENTITY write (rank 2) exactly once.
1420fn finalize_forced_death(
1421    sched: &mut GlobalSchedState,
1422    task_id: TaskId,
1423    exit_code: i32,
1424    task_pid: Pid,
1425) -> (Option<TaskId>, Option<usize>) {
1426    // Single SCHED_IDENTITY.write() for all identity mutations.
1427    lockdep_acquire(LockRank::IdentityW, None);
1428    let mut identity = SCHED_IDENTITY.write();
1429    let ipi_reparent = reparent_children(sched, &mut identity, task_id);
1430    let parent = identity.parent_of.remove(&task_id);
1431    lockdep_release(LockRank::IdentityW);
1432    drop(identity);
1433
1434    if let Some(parent_id) = parent {
1435        sched.zombies.insert(task_id, (exit_code, task_pid));
1436        let (_, ipi_wake) = sched.wake_task_locked(parent_id);
1437        (Some(parent_id), ipi_reparent.or(ipi_wake))
1438    } else {
1439        (None, ipi_reparent)
1440    }
1441}
1442
1443/// Performs the reparent children operation.
1444/// Reparent children of a dying task to PID 1 (init), or drop parent links
1445/// if PID 1 is not available.
1446///
1447/// # Orphan policy
1448///
1449/// - **PID 1 exists:** Orphans are reparented to init, which is responsible
1450///   for reaping them. This matches standard Unix semantics.
1451/// - **PID 1 does not exist:** Parent links are dropped entirely. Orphans
1452///   become parentless : they continue running but cannot be `wait()`-ed on.
1453///   This avoids the nondeterministic fallback of adopting an arbitrary task
1454///   (which might be short-lived or unsuitable for reaping).
1455/// - **PID 1 is the dying task:** Same as above : parent links are dropped.
1456fn reparent_children(
1457    sched: &mut GlobalSchedState,
1458    identity: &mut SchedIdentity,
1459    dying: TaskId,
1460) -> Option<usize> {
1461    let children = match identity.children_of.remove(&dying) {
1462        Some(c) => c,
1463        None => return None,
1464    };
1465
1466    // Preferred reaper: PID 1 (standard init process).
1467    let init_id = identity.pid_to_task.get(&1).copied();
1468
1469    let Some(init_id) = init_id else {
1470        // No PID 1: drop parent links. Orphans become parentless.
1471        for child in &children {
1472            identity.parent_of.remove(child);
1473        }
1474        return None;
1475    };
1476    if init_id == dying {
1477        // PID 1 is dying : cannot reparent to self. Drop parent links.
1478        for child in &children {
1479            identity.parent_of.remove(child);
1480        }
1481        return None;
1482    }
1483
1484    let mut has_zombie = false;
1485    let init_children = identity.children_of.entry(init_id).or_default();
1486    for child in children {
1487        if !has_zombie && sched.zombies.contains_key(&child) {
1488            has_zombie = true;
1489        }
1490        identity.parent_of.insert(child, init_id);
1491        init_children.push(child);
1492    }
1493    if has_zombie {
1494        let (_, ipi) = sched.wake_task_locked(init_id);
1495        ipi
1496    } else {
1497        None
1498    }
1499}
1500
1501/// Performs the cleanup task resources operation.
1502///
1503/// Called when a task exits or is killed to release ports, capabilities,
1504/// and user address space mappings.
1505///
1506/// # Safety
1507/// Must be called with the scheduler lock held and the task no longer
1508/// accessible from any global map (all_tasks, current_task, etc.).
1509fn queue_silo_cleanup(task_id: TaskId) {
1510    let mut guard = PENDING_SILO_CLEANUPS.lock();
1511    // Last-resort trade-off: if the deferred queue is full we drop the entry
1512    // (log only) instead of panicking the kernel when many tasks die at once.
1513    // The authoritative silo map entry remains until `on_task_terminated` runs,
1514    // so this never corrupts silo membership accounting.
1515    if let Err(_) = guard.push_back(task_id) {
1516        log::error!(
1517            "[silo] pending cleanup queue full; task {} cleanup deferred/dropped",
1518            task_id.as_u64()
1519        );
1520    }
1521}
1522
1523pub fn flush_deferred_silo_cleanups() {
1524    // Binding owners are queued only from the reap path, which holds the
1525    // scheduler lock; release the mount/namespace tables outside any lock.
1526    let mut bindings = FixedQueue::<Pid, PENDING_SILO_CLEANUPS_CAPACITY>::new();
1527    if let Some(mut guard) = PENDING_BINDING_CLEANUPS.try_lock() {
1528        core::mem::swap(&mut *guard, &mut bindings);
1529    }
1530    while let Some(tgid) = bindings.pop_front() {
1531        crate::namespace::release_owned_by(tgid);
1532        crate::vfs::unmount_owned_by(tgid);
1533    }
1534
1535    let mut guard = match PENDING_SILO_CLEANUPS.try_lock() {
1536        Some(g) => g,
1537        None => return, // Lock held by preempted task or other CPU, skip safely
1538    };
1539    if guard.is_empty() {
1540        return;
1541    }
1542    let mut drained = FixedQueue::<TaskId, PENDING_SILO_CLEANUPS_CAPACITY>::new();
1543    core::mem::swap(&mut *guard, &mut drained);
1544    drop(guard);
1545    while let Some(task_id) = drained.pop_front() {
1546        crate::silo::on_task_terminated(task_id);
1547    }
1548}
1549
1550pub(crate) fn cleanup_task_resources(task: &Arc<Task>) {
1551    crate::ipc::port::cleanup_ports_for_task(task.id);
1552    // Cancel calls owned by this task; a late server reply must fail EPIPE.
1553    crate::ipc::v2::cleanup_for_task(task.id);
1554    queue_silo_cleanup(task.id);
1555
1556    // Kernel-owned user stack (/thread/create): reclaim if not already done
1557    // by exit_current_task. take()-based, so this is a cheap no-op otherwise.
1558    crate::process::thread_ops::reclaim_kernel_user_stack(task);
1559
1560    // SAFETY: strong_count is racy (a concurrent get_task_by_id may temporarily
1561    // hold an extra Arc ref). Worst case: cleanup is deferred until the last ref
1562    // drops elsewhere - no resource leak, just delayed release.
1563    let is_last_process_ref = Arc::strong_count(&task.process) == 1;
1564    if !is_last_process_ref {
1565        return;
1566    }
1567
1568    // Last reference to the process: release every v2 handle it holds.
1569    crate::ipc::v2::cleanup_process(&task.process);
1570
1571    // Namespace/VFS bindings owned by this thread group (normally already
1572    // released by `exit_current_task`; queued here for kill/reap paths, which
1573    // run under the scheduler lock where VFS access is forbidden).
1574    let mut queued = PENDING_BINDING_CLEANUPS.lock();
1575    if queued.push_back(task.tgid).is_err() {
1576        log::error!(
1577            "[ipc] pending binding cleanup queue full; tgid {} bindings leaked",
1578            task.tgid
1579        );
1580    }
1581
1582    unsafe {
1583        (&mut *task.process.fd_table.get()).close_all();
1584        let capabilities = (&*task.process.capabilities.get()).take_all();
1585        for capability in &capabilities {
1586            crate::capability::release_capability(capability, Some(task.id));
1587        }
1588        // Drop the lock-free silo cache: the authoritative map entry is
1589        // removed asynchronously by `on_task_terminated`.
1590        task.silo_id.store(0, Ordering::Relaxed);
1591    }
1592
1593    let as_ref = task.process.address_space_arc();
1594    if !as_ref.is_kernel() && Arc::strong_count(&as_ref) == 1 {
1595        as_ref.unmap_all_user_regions();
1596    }
1597}
1598
1599/// Trace putc routed to the arch serial backend (replaces port 0xE9 debug).
1600#[inline]
1601pub(crate) fn debug_trace_putc(c: u8) {
1602    crate::arch::serial::_print(format_args!("{}", c as char));
1603}