-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathprocess.rs
More file actions
11284 lines (10395 loc) · 477 KB
/
Copy pathprocess.rs
File metadata and controls
11284 lines (10395 loc) · 477 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::fork::PAGE_REF_COUNT;
use crate::signal::PendingSignals;
use crate::signal::{SigAction, NSIG};
use crate::syscall::{SyscallError, VfsStat};
use crate::time;
use alloc::alloc::{AllocError, Allocator, Global, Layout};
use alloc::{
boxed::Box,
string::String,
sync::{Arc, Weak},
vec::Vec,
};
use cap::CapTable;
use core::any::Any;
use core::ptr::NonNull;
#[cfg(feature = "kcov")]
use core::sync::atomic::AtomicPtr;
use core::sync::atomic::{AtomicBool, AtomicI32, AtomicU64, AtomicUsize, Ordering};
use lsm::ProcessCtx as LsmProcessCtx; // R25-7 FIX: Import LSM for task_exit hook
use mm::memory::FrameAllocator;
use mm::page_table;
use mm::{
allocation_charge_bytes, arc_charge_bytes, try_reserve_heap, vec_charge_bytes, AdmittedMap,
AdmittedSet, AdmittedVec, HeapCharge, HeapClass, HeapReservation, PreparedAdmittedVecCapacity,
RetiredAdmittedVecCapacity,
};
use seccomp::{PledgeState, SeccompState};
use spin::{Mutex, Once, RwLock};
// D2-ARC: fixed held-pid registry for the alloc-free process-registry transaction.
use core::cell::Cell;
// G.1 Observability: Watchdog integration for hung-task detection
use trace::watchdog::{register_watchdog, unregister_watchdog, WatchdogConfig, WatchdogHandle};
use x86_64::{
registers::control::{Cr3, Cr3Flags},
structures::paging::{
FrameAllocator as X64FrameAllocator, Page, PageTable, PageTableFlags, PhysFrame, Size4KiB,
},
PhysAddr, VirtAddr,
};
/// 进程ID类型
pub type ProcessId = usize;
/// R65-19 / M4-1: starvation threshold — a Ready task that waits this many timer ticks
/// without running earns one dynamic-priority boost level. Lifted to a `pub` module const
/// (was function-local in `check_and_boost_starved`) so the timer tick can gate on it
/// without calling the now-deferred boost method in IRQ (M4-1 latch-on-tick).
pub const STARVATION_THRESHOLD: u64 = 100;
/// 进程优先级(0-139,数值越小优先级越高)
pub type Priority = u8;
/// E.4 Priority Inheritance: Futex 键 (tgid, uaddr)
///
/// Used for tracking which futex a task is waiting on (for transitive PI)
/// and as keys in the PI boost map.
pub type FutexKey = (ProcessId, usize);
// ============================================================================
// Exact-lifetime process Arc admission (RF180-40)
// ============================================================================
/// Maximum number of simultaneously live process Arc control blocks.
///
/// `HeapClass::CoreProcess` is capped at 512 KiB, and the compile-time assertion
/// below proves every `Mutex<Process>` payload consumes at least 512 bytes. The
/// byte ledger therefore rejects a 1025th process Arc before this fixed, heap-
/// independent registry can be exhausted.
const PROCESS_ARC_CHARGE_SLOTS: usize = 1024;
struct ProcessArcChargeSlot {
generation: u64,
allocated: bool,
charge: HeapCharge,
}
static PROCESS_ARC_CHARGES: Mutex<[Option<ProcessArcChargeSlot>; PROCESS_ARC_CHARGE_SLOTS]> =
Mutex::new([const { None }; PROCESS_ARC_CHARGE_SLOTS]);
static NEXT_PROCESS_ARC_GENERATION: AtomicU64 = AtomicU64::new(1);
/// Allocator carried by every process `Arc` and `Weak` handle.
///
/// RF180-40 FIX: storing the outer-Arc charge inside `Process` released it when
/// the last strong owner destroyed the payload, even though procfs can retain a
/// `Weak` and keep the control block allocated indefinitely. The allocator owns
/// the charge in static, generation-tagged storage instead. `Arc` calls
/// `deallocate` only after the final strong and weak reference disappears; this
/// implementation deallocates the control block first and releases admission
/// second. A copied allocator is a single-use capability and cannot allocate a
/// second uncharged block.
#[derive(Clone, Copy, Debug)]
pub struct ProcessArcAllocator {
slot: u16,
generation: u64,
}
impl ProcessArcAllocator {
fn try_install(charge: HeapCharge) -> Result<Self, HeapCharge> {
let generation = match NEXT_PROCESS_ARC_GENERATION.fetch_update(
Ordering::AcqRel,
Ordering::Acquire,
|current| current.checked_add(1),
) {
Ok(generation) => generation,
Err(_) => return Err(charge),
};
let mut charge = Some(charge);
let mut slots = PROCESS_ARC_CHARGES.lock();
for (index, slot) in slots.iter_mut().enumerate() {
if slot.is_none() {
*slot = Some(ProcessArcChargeSlot {
generation,
allocated: false,
charge: charge.take().expect("process Arc charge moved once"),
});
return Ok(Self {
slot: index as u16,
generation,
});
}
}
Err(charge.expect("process Arc slot scan retained charge"))
}
fn take_charge(self) -> HeapCharge {
let mut slots = PROCESS_ARC_CHARGES.lock();
let slot = slots
.get_mut(self.slot as usize)
.expect("RF180-40 process Arc allocator slot out of range");
match slot.as_ref() {
Some(entry) if entry.generation == self.generation => {}
Some(_) => panic!("RF180-40 stale process Arc allocator generation"),
None => panic!("RF180-40 process Arc charge released twice"),
}
slot.take()
.expect("validated process Arc charge disappeared")
.charge
}
fn cancel_failed_allocation(self) {
drop(self.take_charge());
}
}
unsafe impl Allocator for ProcessArcAllocator {
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
{
let mut slots = PROCESS_ARC_CHARGES.lock();
let Some(entry) = slots.get_mut(self.slot as usize).and_then(Option::as_mut) else {
return Err(AllocError);
};
if entry.generation != self.generation || entry.allocated {
return Err(AllocError);
}
entry.allocated = true;
}
match Global.allocate(layout) {
Ok(allocation) => Ok(allocation),
Err(error) => {
let mut slots = PROCESS_ARC_CHARGES.lock();
if let Some(entry) = slots.get_mut(self.slot as usize).and_then(Option::as_mut) {
if entry.generation == self.generation {
entry.allocated = false;
}
}
Err(error)
}
}
}
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
// Memory first, admission second: a concurrent creator cannot consume
// these bytes while the old control block is still physically live.
unsafe { Global.deallocate(ptr, layout) };
drop(self.take_charge());
}
}
pub type ProcessArc = Arc<Mutex<Process>, ProcessArcAllocator>;
pub type ProcessWeak = Weak<Mutex<Process>, ProcessArcAllocator>;
/// mmap 默认起始地址
// ST-K3 FIX: moved 0x4000_0000 (1 GiB) → 0x10_0000_0000 (64 GiB). The old
// window [1 GiB, 1.25 GiB) sat INSIDE the 0-4 GiB identity map that
// `create_fresh_address_space`/`deep_copy_identity_for_user` copy into every
// user address space as 2 MiB huge supervisor pages (only 4-6 MiB is split
// for the ELF image), so `map_to` failed with ParentEntryHugePage on EVERY
// frame-backed anonymous mmap — no userspace mmap had ever succeeded
// (PROT_NONE reservations skip map_page, which masked it). 64 GiB is far
// past the identity map's 4 GiB coverage (headroom for future MMIO/identity
// growth), far below USER_STACK_TOP (0x7FFF_FFFF_E000) and USER_SPACE_TOP
// (128 TiB); PDPT entries there are unused in the copied table, so map_to
// builds fresh user-accessible PD/PTs. pub(crate) so the exec reset uses THIS
// constant instead of a duplicated literal (the two sites can never drift).
// Diagnosed via the ST-K3 Phase D E6 tag: err=ParentEntryHugePage, booted
// evidence in docs/review/design/st-k3-mmap-enomem-design.md.
// Fully pub (not pub(crate)): the boot-time regression test
// `st_k3_mmap_window_clear` in the `kernel` crate walks a fresh user AS's
// tables over [DEFAULT_MMAP_BASE, +security::MMAP_MAX_OFFSET] and hard-FAILs
// if any inherited huge-page parent entry covers the window. The value is a
// layout constant, not a secret (the KASLR offset is the runtime entropy).
pub const DEFAULT_MMAP_BASE: usize = 0x10_0000_0000;
/// 页大小
const PAGE_SIZE: u64 = 0x1000;
/// 每进程内核栈基址(PML4[511]/PDPT[508],在共享内核空间内)
pub const KSTACK_BASE: u64 = 0xFFFF_FFFF_0000_0000;
/// 每进程内核栈步长(32KB 栈 + 4KB 守护页 = 36KB)
// ST-K3 FIX (fork double-fault): 16 KiB per-process kernel stacks cannot host
// the Ring-3 process-creation path — `Process::try_new_pcb` alone reserves a
// ~12.4 KiB frame (LLVM stack probes `sub $0x1000,%rsp` ×3 + 0xC0; the on-stack
// `Process` temporary), and the syscall entry + dispatcher + sys_clone +
// sys_fork + create_process frames sit under it. The third probe touched the
// guard page → #PF → the handler could not push onto the dead stack → double
// fault at try_new_pcb+0x36, deterministic (RIP tracked the KASLR slide with
// constant link offset 0x21BF86). Never seen before because every prior
// process creation ran on fat boot-context stacks — no Ring-3 fork/clone had
// ever reached create_process. 32 KiB gives ~2.6× headroom over the measured
// worst frame; the in-place-PCB-construction refactor that removes the class
// is tracked separately in the plan.
pub const KSTACK_STRIDE: u64 = 0x9000;
/// 内核栈页数(32KB = 8 页)
const KSTACK_PAGES: usize = 8;
/// 守护页数
const KSTACK_GUARD_PAGES: usize = 1;
/// `map_to` can request at most three intermediate frames per 4 KiB leaf.
/// The deliberately conservative per-stack ledger remains tiny and makes all
/// post-admission mapping/rollback bookkeeping allocation-free.
const KSTACK_PT_LEDGER_CAPACITY: usize = KSTACK_PAGES * 3;
struct KernelStackPtRecorder<'a> {
inner: &'a mut FrameAllocator,
frames: [Option<PhysFrame<Size4KiB>>; KSTACK_PT_LEDGER_CAPACITY],
len: usize,
}
impl<'a> KernelStackPtRecorder<'a> {
fn new(inner: &'a mut FrameAllocator) -> Self {
Self {
inner,
frames: [None; KSTACK_PT_LEDGER_CAPACITY],
len: 0,
}
}
fn into_record(
self,
) -> (
[Option<PhysFrame<Size4KiB>>; KSTACK_PT_LEDGER_CAPACITY],
usize,
) {
(self.frames, self.len)
}
}
unsafe impl X64FrameAllocator<Size4KiB> for KernelStackPtRecorder<'_> {
fn allocate_frame(&mut self) -> Option<PhysFrame<Size4KiB>> {
// Refuse before allocation if the fixed provenance ledger is full.
// A live but unrecorded table frame would make failure rollback unable
// to prove ownership.
if self.len == KSTACK_PT_LEDGER_CAPACITY {
return None;
}
let frame = self.inner.allocate_frame()?;
self.frames[self.len] = Some(frame);
self.len += 1;
Some(frame)
}
}
/// G.1: Default watchdog timeout for hung-task detection (10 seconds).
///
/// If a task hasn't been scheduled (heartbeat) for this duration, it will
/// trigger the hung_task tracepoint. 10s is a reasonable default that catches
/// true hangs while allowing normal blocking operations.
const WATCHDOG_TIMEOUT_MS: u64 = 10_000;
/// 调度器清理回调类型
///
/// RF178-33 / P1-B: identity is `(pid, generation)`, not PID alone.
/// `cleanup_zombie` detaches the table slot before this fires; a recycled PID
/// may already own a live PCB under the same numeric id. The callback must
/// only purge queue membership for the reaped generation (see
/// `Scheduler::remove_process`).
type SchedulerCleanupCallback = fn(ProcessId, u64);
/// IPC清理回调类型
/// R37-2 FIX (Codex review): Pass both PID and TGID to avoid deadlock.
/// R114-1 FIX: The callback is invoked by `cleanup_zombie()` AFTER detaching the PCB from
/// `PROCESS_TABLE` and releasing the table lock. This avoids deadlocks from IPC/futex cleanup
/// paths that call `thread_group_size()` or `get_process()` (both re-lock `PROCESS_TABLE`).
/// R75-2 FIX: Also pass IPC namespace ID for per-namespace endpoint cleanup.
/// R180-5 FIX: Also pass the reaped process **generation**. The PID slot may already
/// be reused by a successor before Phase 2 runs; callbacks must key identity by
/// `(pid, generation)` (mirrors RF178-33 / P1-B scheduler cleanup).
type IpcCleanupCallback = fn(ProcessId, ProcessId, cap::NamespaceId, u64); // (pid, tgid, ipc_ns_id, generation)
/// Exit-time robust-futex callback. The process subsystem invokes this once
/// after publishing `Zombie`, while the dying task's address space is still
/// retained. The callback receives the generation-bound identity plus the TID
/// as observed in the task's owning PID namespace (captured before teardown
/// detaches that namespace chain), so the userspace owner word can be matched
/// without leaking or guessing a global PID.
pub type RobustFutexCleanupCallback = fn(ProcessId, ProcessId, u64, ProcessId); // (pid, tgid, generation, owner_tid)
/// R180-19: identity-bound token for a pre-staged scheduler admission.
///
/// The scheduler inserts the child into a fallible ready-queue slot while the
/// child is still `Provisioning`. Fork/clone then complete every remaining
/// fallible operation and consume the token to publish `Ready` without any heap
/// growth. `(pid, generation)` prevents cancellation or commit from touching a
/// recycled PID, while `cpu_id + priority` identify the exact reserved bucket.
/// The pinned Arc lets COMMIT publish the exact PCB without rediscovering it
/// under a ready-queue lock after the transaction's point of no return.
pub struct SchedulerAddToken {
pub cpu_id: usize,
pub priority: Priority,
pub pid: ProcessId,
pub generation: u64,
pub process: ProcessArc,
}
/// Recoverable scheduler-admission failures. They are deliberately coarse:
/// callers fail the process-creation transaction before publication.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SchedulerAddError {
Unavailable,
NoMemory,
NoEligibleCpu,
InvalidState,
}
pub type SchedulerReserveCallback = fn(ProcessArc) -> Result<SchedulerAddToken, SchedulerAddError>;
pub type SchedulerCommitCallback = fn(SchedulerAddToken);
pub type SchedulerCancelCallback = fn(SchedulerAddToken);
#[derive(Clone, Copy)]
struct SchedulerAdmissionCallbacks {
reserve: SchedulerReserveCallback,
commit: SchedulerCommitCallback,
cancel: SchedulerCancelCallback,
}
/// RAII ownership of one exact scheduler queue slot.
///
/// Dropping an uncommitted permit removes the non-runnable placeholder without
/// allocation. `commit` is intentionally infallible: the queue entry and all
/// of its backing capacity already exist.
pub struct SchedulerAddPermit {
token: Option<SchedulerAddToken>,
commit: SchedulerCommitCallback,
cancel: SchedulerCancelCallback,
armed: bool,
}
impl SchedulerAddPermit {
#[inline]
pub fn commit(mut self) {
let token = self
.token
.take()
.expect("scheduler admission permit consumed twice");
(self.commit)(token);
self.armed = false;
}
}
impl Drop for SchedulerAddPermit {
fn drop(&mut self) {
if self.armed {
let token = self
.token
.take()
.expect("armed scheduler admission permit lost its token");
(self.cancel)(token);
}
}
}
/// Futex 唤醒回调类型
///
/// 线程退出时调用,唤醒等待在 clear_child_tid 地址上的进程
/// 参数: (tgid, uaddr, max_wake_count) -> 实际唤醒数量
pub type FutexWakeCallback = fn(ProcessId, usize, usize) -> usize;
/// E.5 Cpuset: Callback for task joining a cpuset
///
/// Called when a new process is created (fork/clone) to update cpuset task count.
/// Parameter: cpuset_id (u32)
pub type CpusetTaskJoinedCallback = fn(u32);
/// E.5 Cpuset: Callback for task leaving a cpuset
///
/// Called when a process exits to update cpuset task count.
/// Parameter: cpuset_id (u32)
pub type CpusetTaskLeftCallback = fn(u32);
/// H.3 KPTI: Callback to update per-CPU GS-addressable CR3 pair
///
/// Called during context switch to keep the syscall entry/exit assembly's
/// GS-relative CR3 values in sync with the loaded address space.
/// Parameters: (user_cr3, kernel_cr3) — physical addresses.
///
/// When KPTI is disabled, both values are the same (causing the cmp/je
/// skip pattern in syscall_entry_stub to bypass the CR3 switch entirely).
pub type KptiCr3UpdateCallback = fn(u64, u64);
/// 最大文件描述符数量(每进程)
pub const MAX_FD: i32 = 256;
const FD_RESERVATION_WORDS: usize = (MAX_FD as usize + 63) / 64;
/// Linux mutable open-file-description status bits supported by this kernel.
pub const FILE_STATUS_APPEND: u32 = 0x400;
pub const FILE_STATUS_NONBLOCK: u32 = 0x800;
pub const FILE_STATUS_MUTABLE: u32 = FILE_STATUS_APPEND | FILE_STATUS_NONBLOCK;
/// F_SETFL ignores access/creation bits, but must not pretend to enable SIGIO.
pub fn mutable_file_status_bits(flags: u32) -> Result<u32, SyscallError> {
const O_ASYNC: u32 = 0x2000;
if flags & O_ASYNC != 0 {
return Err(SyscallError::EOPNOTSUPP);
}
Ok(flags & FILE_STATUS_MUTABLE)
}
#[derive(Clone, Copy)]
pub(crate) struct ConsoleFile {
pub(crate) readable: bool,
}
impl FileOps for ConsoleFile {
fn status_flags(&self) -> Result<u32, SyscallError> {
Ok(if self.readable { 0 } else { 1 })
}
fn clone_box(&self) -> Result<FileDescriptor, ()> {
FileDescriptor::try_new(*self, HeapClass::CoreProcess)
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn type_name(&self) -> &'static str {
"ConsoleFile"
}
fn stat(&self) -> Result<VfsStat, SyscallError> {
Ok(VfsStat {
dev: 0,
ino: 4,
nlink: 1,
mode: 0o020666,
uid: 0,
gid: 0,
pad0: 0,
rdev: 0x501,
size: 0,
blksize: 4096,
blocks: 0,
atime_sec: 0,
atime_nsec: 0,
mtime_sec: 0,
mtime_nsec: 0,
ctime_sec: 0,
ctime_nsec: 0,
unused0: 0,
unused1: 0,
unused2: 0,
})
}
}
/// 文件操作 trait
///
/// 定义文件描述符必须实现的操作,支持:
/// - 克隆(用于 fork)
/// - 向下转型(用于类型特定操作)
/// - 调试输出
///
/// 由于循环依赖限制,kernel_core 定义此 trait,具体类型(如 PipeHandle)
/// 在各自的 crate(如 ipc)中实现。
pub trait FileOps: Send + Sync {
/// Current access/status flags for F_GETFL. Namespace descriptors are
/// read-only; mutable file, pipe and socket descriptions override this.
fn status_flags(&self) -> Result<u32, SyscallError> {
Ok(0)
}
/// Update shared description status without allocation or blocking I/O.
/// CLOEXEC stays exclusively in the descriptor table. Unsupported kinds
/// reject mutable status instead of reporting a successful no-op.
fn set_status_flags(&self, flags: u32) -> Result<(), SyscallError> {
if mutable_file_status_bits(flags)? != 0 {
return Err(SyscallError::EOPNOTSUPP);
}
Ok(())
}
/// Fallibly clone this file descriptor (used by fork/dup).
///
/// An infallible clone API could abort the kernel when descriptor storage
/// or admission is exhausted. Callers propagate `Err(())` as a normal
/// rollback/`ENOMEM` path instead.
fn clone_box(&self) -> Result<FileDescriptor, ()>;
/// Compatibility alias for callers that use the explicit fallible name.
fn try_clone_box(&self) -> Result<FileDescriptor, ()> {
self.clone_box()
}
/// 获取 Any 引用用于向下转型
fn as_any(&self) -> &dyn Any;
/// 获取 Any 可变引用用于向下转型(U.S2 SLICE-3B: set_cap_id after VFS returns)
fn as_any_mut(&mut self) -> &mut dyn Any;
/// 获取类型名称(用于调试)
fn type_name(&self) -> &'static str;
/// U.S3-B: report the CapId this fd carries, if any, so the generic fd
/// lifecycle paths (`remove_fd`, dup increment, exec-cloexec drain, process
/// exit) can decrement its refcount and revoke-at-0 WITHOUT downcasting to
/// each concrete type.
///
/// Default `None` = this fd kind carries no capability (namespace fds:
/// mount/ipc/net/user — they refcount the namespace object itself, not a
/// CapEntry). A cap-BEARING implementor (`SocketFile`, `PipeHandle` since
/// U.S2 SLICE-3; file fds in SLICE-3B) MUST override this AND have a
/// structural self-test asserting the override — a new default-bearing
/// trait method silently makes the specialized path dead for any
/// implementor that forgot to override it (the dev-v35 missing-override
/// class; see `run_fileops_cap_id_self_test` +
/// `run_pipe_cap_id_self_test`).
///
/// # Drop / refcount contract (U.S2-SLICE-3, CRITICAL-7)
///
/// A cap-bearing implementor's `Drop` MUST NOT touch any cap_table: cap
/// refcount decrement is the exclusive responsibility of the fd REMOVAL
/// path (`remove_fd` → `decrement_fd_cap` funnel and its exec/exit
/// siblings). Drop MAY close the underlying resource (pipe end, socket).
/// A Drop-side decrement would double-decrement every removed fd (funnel
/// once, Drop again → underflow/premature revoke of a still-referenced
/// cap). The R155-3/R170-6 drop-outside-lock discipline additionally keeps
/// those resource-close side effects (wake_all) off the Process lock.
///
/// # Transient clones and cap lifetime (U.S2-SLICE-3, CRITICAL-10)
///
/// `clone_box()` copies are refcount-PURE (U.S3-A2) and carry the SAME
/// CapId. The I/O paths (fd_read/fd_write callbacks) clone the handle and
/// drop the Process lock before blocking I/O (R41-3); such transient
/// clones do NOT extend cap lifetime. If another task drives the cap's
/// refcount to 0 mid-I/O (last close → revoke), the in-flight clone's
/// cap_id points to a REVOKED CapId. That is benign today (I/O paths do
/// not consult cap rights); any future rights-checking I/O path must
/// tolerate `InvalidCapId` (generation mismatch) and map it to EBADF
/// ("fd closed during I/O"), never panic.
fn cap_id(&self) -> Option<cap::CapId> {
None
}
/// U.S2 SLICE-3B: Set the CapId for this file descriptor.
///
/// Called by syscall layer after allocating a capability but before installing
/// the fd. Only implemented by cap-bearing types (FileHandle for regular files,
/// PipeHandle for pipes, SocketFile for sockets). The default no-op is for
/// non-cap-bearing types (namespace fds, special files).
///
/// # Contract
///
/// - Must be called exactly once per fd, immediately after cap allocation
/// - Must store the cap_id so that subsequent cap_id() calls return Some(id)
/// - Must use interior mutability (OnceCell or similar) since this is &self
/// - Must panic if called twice (OnceCell::set returns Err on second call)
///
/// The default no-op silently ignores the cap_id, which is correct for types
/// that don't carry capabilities (they never call this method).
fn set_cap_id(&self, _id: cap::CapId) {
// Default: no-op for non-cap-bearing types
}
/// R41-1 FIX: 获取文件状态信息(用于 fstat)
///
/// 默认返回 EBADF,子类型应覆盖此方法返回正确的元数据。
/// FileHandle、Ext2File 应返回 inode 元数据,
/// PipeHandle 应返回 S_IFIFO 模式。
fn stat(&self) -> Result<VfsStat, SyscallError> {
Err(SyscallError::EBADF)
}
/// M0-6 poll/select: classify this fd for a non-consuming readiness probe.
///
/// Called under the Process lock by the poll/select classify pass; the returned
/// `PollArm` is then probed OUTSIDE the lock. Because `kernel_core` cannot
/// downcast the concrete types living in the `ipc`/`vfs` crates (they depend on
/// `kernel_core`, not the reverse), each implementor overrides this instead of a
/// central downcast — the same cycle-avoiding pattern as `FD_READ_CALLBACK`.
///
/// The default is `AlwaysReady` (Linux DEFAULT_POLLMASK: a fd kind with no
/// blocking read/write always reports readable+writable). Regular files
/// (`FileHandle`/`Ext2File`) and namespace fds keep the default. NOTE: a
/// `/dev/console` `FileHandle` is a KNOWN-WRONG case under this default (its
/// `read_at` is a non-blocking `keyboard_read` that returns 0 when empty, so
/// poll would spuriously report POLLIN) — no in-tree consumer opens it today;
/// a char-device override rides this same mechanism as a tracked residual.
fn poll_arm(&self) -> crate::poll::PollArm {
crate::poll::PollArm::AlwaysReady
}
}
impl core::fmt::Debug for dyn FileOps {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "FileOps({})", self.type_name())
}
}
/// 文件描述符类型
/// Detached, admitted backing for one concrete file-operations value.
///
/// RF180-37: the allocation and its lifetime charge are acquired before the
/// caller performs externally visible work. Finalization only initializes the
/// already-allocated slot and unsizes its Box; it cannot allocate or fail.
#[must_use = "dropping a prepared descriptor releases its private allocation and admission"]
pub struct PreparedFileDescriptor<T: FileOps + 'static> {
storage: Box<core::mem::MaybeUninit<T>>,
charge: Option<HeapCharge>,
}
impl<T: FileOps + 'static> PreparedFileDescriptor<T> {
pub fn try_new(class: HeapClass) -> Result<Self, ()> {
let bytes = allocation_charge_bytes(core::mem::size_of::<T>(), core::mem::align_of::<T>())
.map_err(|_| ())?;
let reservation = try_reserve_heap(class, bytes).map_err(|_| ())?;
let storage = Box::<T>::try_new_uninit().map_err(|_| ())?;
let charge = reservation.commit().map_err(|_| ())?;
Ok(Self {
storage,
charge: Some(charge),
})
}
/// Initialize and publish the already-admitted descriptor allocation.
///
/// This function is intentionally infallible. `storage` is declared before
/// `charge` both here and in [`FileDescriptor`], so every rollback and live
/// drop destroys/deallocates the concrete value before releasing admission.
pub fn finalize(mut self, value: T) -> FileDescriptor {
unsafe {
self.storage.as_mut_ptr().write(value);
}
let storage = self.storage;
let concrete = unsafe { storage.assume_init() };
let ops: Box<dyn FileOps> = concrete;
let charge = self
.charge
.take()
.expect("prepared file descriptor lost its heap charge");
FileDescriptor {
ops,
_charge: charge,
}
}
}
/// Exact-lifetime owner for a heap-allocated file-operations value.
///
/// RF180-37: this replaces the raw `Box<dyn FileOps>` alias. The trait object is
/// the first field, so its concrete value is dropped and its Box is deallocated
/// before the second field releases the whole-heap charge. Embedding the charge
/// inside the concrete FileOps value is not exact: that field is destroyed while
/// the outer Box allocation is still live.
pub struct FileDescriptor {
ops: Box<dyn FileOps>,
_charge: HeapCharge,
}
impl FileDescriptor {
/// Admit and allocate a descriptor before constructing/publishing it.
#[inline]
pub fn try_prepare<T: FileOps + 'static>(
class: HeapClass,
) -> Result<PreparedFileDescriptor<T>, ()> {
PreparedFileDescriptor::try_new(class)
}
/// Convenience for side-effect-free values. Transactions with external
/// ownership changes should call `try_prepare` first and `finalize` last.
#[inline]
pub fn try_new<T: FileOps + 'static>(value: T, class: HeapClass) -> Result<Self, ()> {
Self::try_prepare(class).map(|prepared| prepared.finalize(value))
}
#[inline]
pub fn try_clone(&self) -> Result<Self, ()> {
self.ops.try_clone_box()
}
}
impl core::ops::Deref for FileDescriptor {
type Target = dyn FileOps;
#[inline]
fn deref(&self) -> &Self::Target {
self.ops.as_ref()
}
}
impl core::ops::DerefMut for FileDescriptor {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
self.ops.as_mut()
}
}
impl AsRef<dyn FileOps> for FileDescriptor {
#[inline]
fn as_ref(&self) -> &(dyn FileOps + 'static) {
self.ops.as_ref()
}
}
impl core::fmt::Debug for FileDescriptor {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
self.ops.fmt(f)
}
}
/// 内核栈分配错误
#[derive(Debug, Clone, Copy)]
pub enum KernelStackError {
/// 栈地址已被映射(PID 复用时可能发生)
AlreadyMapped,
/// 物理内存分配失败
AllocationFailed,
/// 页表映射失败
MapFailed,
/// R103-I2 FIX: 地址计算溢出(PID 超出内核栈地址空间范围)
AddressOverflow,
/// R180-12: fixed RCU callback pool is full. No stack was allocated.
CallbackPoolExhausted,
/// The recycled PID's previous stack is still awaiting RCU reclamation.
ReclaimPending,
}
/// 进程创建错误
///
/// SECURITY FIX Z-7: 进程创建失败时必须正确报告错误,而非静默回退
#[derive(Debug, Clone, Copy)]
pub enum ProcessCreateError {
/// 内核栈分配失败
KernelStackAllocFailed(KernelStackError),
/// R29-5 FIX: PID 空间耗尽(内核栈地址空间溢出)
PidExhausted,
/// Whole-heap admission or a fallible PCB allocation failed.
OutOfMemory,
/// F.1: PID namespace chain assignment failed
NamespaceError,
}
/// R29-5 FIX: Maximum PID before kernel stack address overflow
///
/// Each process gets a kernel stack at KSTACK_BASE + pid * KSTACK_STRIDE.
/// After this many PIDs, new stacks would overflow into other kernel memory.
/// Calculation: (u64::MAX - KSTACK_BASE) / KSTACK_STRIDE ≈ 116,508
/// (ST-K3: recomputed for the 0x9000 stride; was ≈209,715 at 0x5000)
pub const MAX_PID: ProcessId = ((u64::MAX - KSTACK_BASE) / KSTACK_STRIDE) as ProcessId;
/// R106-11 (P0-4): User-visible PID upper bound (Linux default: 32768).
///
/// Bounded separately from `MAX_PID` (kernel stack address space limit) so PID
/// recycling keeps the process table bounded and prevents PID exhaustion under
/// fork/exit churn. Valid PIDs are in [1, PID_MAX].
pub const PID_MAX: ProcessId = 32_768;
/// R180-12: every valid PID has one dedicated RCU stack-lifecycle slot.
/// This is an admission invariant, not a reduction of the PID/task capability.
pub const KERNEL_STACK_ADMISSION_LIMIT: usize = crate::rcu::RCU_STACK_CALLBACK_CAPACITY;
const _: () = assert!(KERNEL_STACK_ADMISSION_LIMIT == PID_MAX);
/// RF180-3 FIX: PIDs detached for Phase-2 reap cleanup remain unavailable
/// until every raw-PID subsystem callback has completed. A thread-group ID
/// remains pinned as well until every member has left `PROCESS_TABLE` and all
/// concurrent Phase-2 cleanups for that group have finished.
///
/// The table slot must be removed before callbacks because they re-enter
/// PROCESS_TABLE, but making the numeric PID immediately reusable lets futex
/// owner/waiter metadata either mutate a successor or survive into it. This
/// fixed bitmap is allocation-free and is consulted by the PID allocator.
const REAPING_PID_WORDS: usize = (PID_MAX + 64) / 64;
struct ReapingPidState {
bits: [u64; REAPING_PID_WORDS],
/// Number of detached members whose Phase-2 cleanup still references this
/// raw TGID. `u16` covers the complete bounded PID space.
tgid_inflight: [u16; PID_MAX + 1],
}
static REAPING_PID_STATE: Mutex<ReapingPidState> = Mutex::new(ReapingPidState {
bits: [0; REAPING_PID_WORDS],
tgid_inflight: [0; PID_MAX + 1],
});
#[inline]
fn reaping_pid_is_set(state: &ReapingPidState, pid: ProcessId) -> bool {
let word = pid / 64;
let bit = pid % 64;
state
.bits
.get(word)
.map(|value| (*value & (1u64 << bit)) != 0)
.unwrap_or(true)
}
#[inline]
fn set_reaping_bit(state: &mut ReapingPidState, pid: ProcessId) {
if let Some(value) = state.bits.get_mut(pid / 64) {
*value |= 1u64 << (pid % 64);
}
}
#[inline]
fn clear_reaping_bit(state: &mut ReapingPidState, pid: ProcessId) {
if let Some(value) = state.bits.get_mut(pid / 64) {
*value &= !(1u64 << (pid % 64));
}
}
/// Begin one detached task's raw-PID/TGID cleanup transaction.
///
/// Caller holds `PROCESS_TABLE`, so allocator observation is atomic with the
/// slot detach. Pinning `tgid` prevents a new process from becoming a leader
/// with the same numeric TGID while surviving old-group members still own
/// futex buckets keyed by `(tgid, uaddr)`.
fn begin_reaping_identity(pid: ProcessId, tgid: ProcessId) {
let mut state = REAPING_PID_STATE.lock();
set_reaping_bit(&mut state, pid);
set_reaping_bit(&mut state, tgid);
if let Some(inflight) = state.tgid_inflight.get_mut(tgid) {
*inflight = inflight
.checked_add(1)
.expect("reaping TGID inflight count exceeds PID_MAX");
}
}
/// Complete one detached task's cleanup and release recyclable identities only
/// after the old thread group has no table members and no other Phase-2 reaper.
fn finish_reaping_identity(pid: ProcessId, tgid: ProcessId) {
// Lock order matches the allocator and all table scanners:
// PROCESS_TABLE -> PCB -> REAPING_PID_STATE.
let table = PROCESS_TABLE.lock();
let group_has_table_member = table.iter().any(|slot| {
slot.as_ref()
.map(|process| process.lock().tgid == tgid)
.unwrap_or(false)
});
let mut state = REAPING_PID_STATE.lock();
let remaining = match state.tgid_inflight.get_mut(tgid) {
Some(inflight) if *inflight > 0 => {
*inflight -= 1;
*inflight
}
_ => {
// Bookkeeping corruption must fail closed: retain both bits.
klog!(
Error,
"RF180-3: missing reaping TGID reference for pid={} tgid={}",
pid,
tgid
);
return;
}
};
// A non-leader PID is no longer present in any raw-PID callback after this
// point. The group leader/TGID has the stronger group-wide lifetime below.
if pid != tgid {
clear_reaping_bit(&mut state, pid);
}
if !group_has_table_member && remaining == 0 {
clear_reaping_bit(&mut state, tgid);
}
}
/// 计算指定 PID 的内核栈虚拟地址范围
///
/// 返回 Ok((栈底, 栈顶)),栈向下生长,栈顶用于 TSS.rsp0
///
/// # R103-I2 FIX
///
/// Returns `Err(KernelStackError::AddressOverflow)` instead of panicking
/// when the PID causes address arithmetic to overflow. Although current
/// callers validate `pid <= MAX_PID`, this function is `pub` and future
/// call sites might not enforce the bound. Returning `Result` makes the
/// contract explicit and prevents kernel panics from propagating.
#[inline]
pub fn kernel_stack_slot(pid: ProcessId) -> Result<(VirtAddr, VirtAddr), KernelStackError> {
// R102-8 FIX: Use checked arithmetic to prevent silent wrapping on invalid PID.
// R103-I2 FIX: Propagate overflow as error instead of panicking.
//
// H.2 Partial KASLR: Apply boot-time random slide to the kernel stack region
// base. This prevents attackers from predicting per-process kernel stack addresses
// even when the kernel text is at a fixed address.
let kstack_base = KSTACK_BASE
.checked_add(security::kernel_stack_slide())
.ok_or(KernelStackError::AddressOverflow)?;
let slot_offset = (pid as u64)
.checked_mul(KSTACK_STRIDE)
.ok_or(KernelStackError::AddressOverflow)?;
let guard_base_addr = kstack_base
.checked_add(slot_offset)
.ok_or(KernelStackError::AddressOverflow)?;
let guard_bytes = KSTACK_GUARD_PAGES as u64 * PAGE_SIZE; // compile-time constant, safe
let stack_base_addr = guard_base_addr
.checked_add(guard_bytes)
.ok_or(KernelStackError::AddressOverflow)?;
let stack_bytes = KSTACK_PAGES as u64 * PAGE_SIZE; // compile-time constant, safe
let stack_top_addr = stack_base_addr
.checked_add(stack_bytes)
.ok_or(KernelStackError::AddressOverflow)?;
Ok((
VirtAddr::new(stack_base_addr),
VirtAddr::new(stack_top_addr),
))
}
/// 为指定 PID 分配并映射带守护页的内核栈
///
/// 在共享的内核页表上映射,所有进程地址空间均可见。
/// 守护页不映射物理帧,访问时会触发页错误。
///
/// # Returns
///
/// 成功返回 (栈底, 栈顶),失败返回错误
pub fn allocate_kernel_stack(
pid: ProcessId,
) -> Result<
(
VirtAddr,
VirtAddr,
PhysFrame<Size4KiB>,
crate::rcu::RcuCallbackPermit,
),
KernelStackError,
> {
let (stack_base, stack_top) = kernel_stack_slot(pid)?;
// R180-12: reserve deferred-reclamation capacity before allocating frames
// or publishing mappings. Pool exhaustion is ordinary creation backpressure.
let reclaim_permit =
crate::rcu::try_reserve_stack_callback(pid).map_err(|error| match error {
crate::rcu::RcuBackpressure::StackCallbackLimit => KernelStackError::ReclaimPending,
crate::rcu::RcuBackpressure::CallbackPoolExhausted => {
KernelStackError::CallbackPoolExhausted
}
})?;
// R103-I2 FIX: Derive guard_base from stack_base using checked arithmetic
// instead of the previous unchecked `KSTACK_BASE + pid as u64 * KSTACK_STRIDE`.
let guard_bytes = KSTACK_GUARD_PAGES as u64 * PAGE_SIZE;
let guard_base_addr = stack_base
.as_u64()
.checked_sub(guard_bytes)
.ok_or(KernelStackError::AddressOverflow)?;
let guard_base = VirtAddr::new(guard_base_addr);
let mut frame_alloc = FrameAllocator::new();
let mut rollback_data_frame: Option<PhysFrame<Size4KiB>> = None;
let mut rollback_table_frames: [Option<PhysFrame<Size4KiB>>; KSTACK_PT_LEDGER_CAPACITY] =
[None; KSTACK_PT_LEDGER_CAPACITY];
let mut rollback_table_count = 0usize;
let mut rollback_quarantine = false;
let mapped_result = unsafe {
page_table::with_current_manager(VirtAddr::new(0), |mgr| {
// 检查整个 slot(守护页 + 栈页)是否已被映射
let total_pages = KSTACK_PAGES + KSTACK_GUARD_PAGES;
for i in 0..total_pages {
let addr = guard_base + (i as u64 * PAGE_SIZE);
if !mgr.page_slot_is_unused(Page::containing_address(addr)) {
return Err(KernelStackError::AlreadyMapped);
}
}
// 分配连续物理帧
let phys_start_frame = frame_alloc
.allocate_contiguous_frames(KSTACK_PAGES)
.ok_or(KernelStackError::AllocationFailed)?;