mirror of
https://github.com/DragonOS-Community/DragonOS.git
synced 2026-09-08 23:57:59 +08:00
master
100
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
ba1694602a |
fix(tty): preserve raw flags across termios ABI conversions (#2267)
TCSETS and the legacy TCSETA family discard flag bits that are not named in the kernel bitflags definitions. This differs from Linux 6.6, which copies the raw flag words and preserves the upper 16 bits when merging legacy termio settings. Preserve all four raw flag words at both ABI conversion boundaries while leaving hardware normalization to the existing driver callbacks. Keep legacy control-character merging and baud-rate extraction unchanged. Use bitflags difference() when restoring old hardware settings after an unsupported driver callback. Unlike the bitflags complement operator, it preserves unnamed bits outside the software-controlled mask, matching tty_termios_copy_hw(). Extend the existing dunitest suite to cover all six set commands, raw flag preservation, legacy control-character tails, input flush behavior, EFAULT without state changes, the 18-byte page-boundary termio ABI and zeroed padding, and console stdin settings. Validation: - Reproduced raw flag loss before the fix: 25 of 26 tty_termios tests passed, with only the new flag-preservation case failing. - After the fix, QEMU x86_64 passed tty_termios (26), tty_tcflush (6), tty_pty_hangup (36), and the existing C termios smoke test. - Verified TCSAFLUSH and legacy settings on ttyS0 stdin, plus a successful apt install of a local test package without the TCSAFLUSH error. - All five added tests passed on host Linux with a PTY. - Kernel build, Rust formatting and whitespace checks passed. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
6a7c3656c6 |
fix(fs): correct ext4 initialization, FAT traversal and truncation (#2265)
* fix(fs): initialize ext4 block bitmaps and guard atomic truncation Treat BLOCK_UNINIT as uninitialized allocation state before validating or scanning a block bitmap. Previously, crossing into a lazily initialized ext4 group could fail delayed writeback with EIO, including when chmod forced pending CodeBuddy installation data to disk. Reuse the mounted system metadata ranges to construct the first bitmap, protect metadata and out-of-group bits, authenticate group descriptors, and verify the free-block count. Share this preparation between the transactional and direct allocators. Publish the initialized bitmap, cleared BLOCK_UNINIT flag, counters and checksums together through the existing transaction path, and retain the original direct rollback image. Keep initialized-bitmap checksum validation and unrelated group flags. Move the temporary O_TRUNC writer guard to the VFS open caller so it spans filesystem open hooks and post-open truncation. This prevents an atomic FUSE O_RDONLY|O_TRUNC open from modifying an executing image before the later ETXTBSY check. Release the temporary guard before returning a read-only descriptor; preserve writable descriptors' existing ownership. Add real-image ext4 regression coverage for both allocation paths, remount/data/fsck consistency, corrupt initialized checksums and an I/O failure during first-initialization preparation. Add dunitest coverage for cross-group write/chmod/fsync/remount and atomic FUSE truncation of a running ELF, including read-only descriptor lifetime. Validation: - make kernel and formatting/diff checks passed. - another_ext4 library: 168 tests passed. - Host ext4 image regression: both allocation paths, checksum rejection and preparation failure/retry passed, with clean e2fsck checks. - DragonOS Ext4InodeIdentity: 37 tests passed. - DragonOS exec write-access coverage: 8 tests passed. - Related FUSE tests: 15/17 passed; the two flag-mask failures also fail on the baseline with identical values. The new regression fails on the baseline and passes after this fix. The FUSE destructive-open behavior also reproduces on Linux 6.8; preserve ETXTBSY while preventing the destructive side effect. Fault injection covers preparation failure, not an exhaustive power-loss matrix. Signed-off-by: longjin <longjin@dragonos.org> * fix(fat): bound sequential reads and detach truncated cluster tails Cold page reads restarted FAT traversal at the first cluster. Reading the 32 MiB ext4 fixture exceeded the FAT entry cache and repeatedly scanned long prefixes, causing the Dunitest timeout before ext4 allocation began. Keep one logical/physical read cursor under the existing inode mutex and invalidate it when the chain can change. Forward reads now traverse only the remaining distance without extra locks or an unbounded index. The new fragmented-read regression also exposed an existing truncate bug: the retained chain still referenced freed clusters. Write EOC before freeing a nonzero truncated tail under the existing FAT lock, reuse the locked deallocation helper, and invalidate both cached chain positions. Correct the FAT16 EOC encoding to 0xffff. Cover cold forward/backward reads, tail reuse, shrink/regrow and rename. The new regression reproduces the truncate failure on the old kernel. Validation: kernel build and formatting checks; Linux FAT32 reference; all 3 DragonOS FAT32 tests; all 37 ext4 inode-identity tests. An independent 32 MiB cold read improved from 59.448 s to 0.311 s. FAT16 runtime testing remains blocked by its existing fixed-root-directory support limitation. Signed-off-by: longjin <longjin@dragonos.org> * fix(fat): retain unlinked files and publish truncation before reclaim Unlink and replacement rename freed cluster chains still owned by open files, mappings and asynchronous writeback. A live read cursor could then return another file's data. Detach the directory entry without freeing the chain, reuse VFS semantic retention, and reclaim only after admission closes and the last owner releases it. Perform fallible cleanup on the existing workqueue mechanism and integrate its completion/error state with sync and unmount. Never retry a partially freed chain. Centralize short-entry submission so detached files can still grow and truncate without writing a directory slot reused by another file. Remove a detached replacement victim from the directory cache even when a later rename step fails. Publish the smaller short entry before cutting and freeing the truncated tail. Keep the new size on reclamation failure and synchronize outer metadata on both outcomes. Continue flushing other files even when reclamation reports a sticky error. Add FAT regressions for cold reads after unlink/replacement, writes and truncate/regrow through the old fd, mmap retention after close, and space reclamation after final munmap and syncfs. Both lifetime cases fail on the old kernel and pass on Linux FAT32 and DragonOS. Final validation passed all five FAT tests, all 37 ext4 inode-identity tests, the kernel build and format checks. Identical post-EOC reclamation EIO injection changes the remounted length from the incorrect 32768 to the expected 4096 bytes. Signed-off-by: longjin <longjin@dragonos.org> * fix(vfs): release inode retention before final mount shutdown File dropped its mount pin before its writer guard. The latter still owns canonical inode Operation retention, so lazy unmount could seal the FAT eviction queue before the final writer release publishes reclamation. Release writer and open-description retention before the mount pin, matching Linux __fput access/dentry release before mntput. Audit and repair the same ordering across the other ownership boundaries: - ResolvedPath releases its operation pin before its mount pin. - Failed File construction releases the transferred operation pin inside the constructor, before its mount-pin parameter is destroyed. - A retained resolved-path owner covers temporary O_TRUNC admission even if File construction or post-open truncation fails. - Exec loading and MM executable-image ownership release deny-write protection before the associated File and its mount pin. Keep the eviction seal protocol and existing close callbacks unchanged; no new lifecycle framework is needed. Validation: kernel build and formatting; DragonOS exec 8/8, FAT32 5/5 and ext4 inode identity 37/37. A manual lazy-unmount/last-writer-close/remount check passed 64 rounds with reclaimed space. The baseline also passed 64 stress rounds, so the race is supported by the destruction-order and ownership audit rather than a claimed deterministic runtime reproduction. Independent agents reviewed the complete PR and follow-up before commit. Signed-off-by: longjin <longjin@dragonos.org> * fix(fat): isolate reclamation workers by filesystem The global single-worker FAT eviction queue made a fast filesystem's syncfs and unmount wait behind another device's slow chain reclamation. Give each FAT filesystem its own serial queue while retaining the existing FIFO epoch, error reporting and eviction seal contracts. Add an owned WorkQueue constructor whose worker waits with a weak queue reference. Pending FAT work retains the filesystem until completion; when the last queue owner disappears, Drop wakes the worker and it exits. This avoids leaking a permanent thread per mount without introducing a new stop protocol or changing existing global workqueues. Return worker creation failure to the mount caller. Validation: kernel build and formatting; FAT32 5/5 and ext4 inode identity 37/37; 64 lazy-unmount/remount rounds with no residual FAT workers. In the same two-volume sample, fast syncfs improved from 367.392 ms to 15.812 ms while slow reclamation continued for another 360.468 ms. Worker count returned from two mounted-filesystem workers to zero after unmount. Independent agents reviewed the complete PR and this follow-up before commit, including empty queues and last-job filesystem destruction. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
87271de2a6 |
feat(mm): unify shared anonymous mappings with internal shmem files (#2266)
* feat(mm): unify shared anonymous mappings with internal shmem files Give shared anonymous mmap and writable-capable shared /dev/zero mappings one authoritative vm_file backed by the existing tmpfs shmem PageCache. Independent mmap calls create independent unlinked inodes; fork, VMA splits and mremap retain the file identity, page offsets and initial backing size. Generalize the internal shmem constructor to accept a diagnostic name and retain its state through an Arc<File>. Remove wrapper-owned logical-size charges and use existing page-cache membership accounting and teardown. Reuse the constructor for System V SHM while keeping IPC permissions, attach accounting, IPC_RMID and SHM_LOCK in the IPC layer. Derive SYSV names from the 32-bit IPC key. Let the inode mmap hook return the final mapping file after originating access checks. Forward this contract through mount, overlayfs and FUSE. Require readable mapping fds even for PROT_NONE, and preserve Linux's VM_SHARED/VM_MAYSHARE distinction for read-only shared mappings. Remove AnonSharedMapping and its fault, futex, mincore, msync and mremap branches. Use ordinary file-cache paths for shared memory and describe retained anonymous-page inodes explicitly so read-only /dev/zero shared futex operations return EFAULT instead of using the device inode key. Render unlinked diagnostic names from real inode metadata in procfs. For architectures without demand paging, populate shared shmem from the same cache and roll back unpublished PTEs, reverse mappings and reservations on failure. Existing architecture-level fault/SIGBUS limitations remain. Add 20 dunitest cases covering mapping identity, sparse and concurrent faults, MAP_POPULATE, fork, split/remap offsets and EOF, futex behavior, permissions, final-reference accounting, and System V diagnostic names. Register the suite in the CI whitelist and no-skip list. Validation: - make kernel and Rust formatting/whitespace checks passed. - All 20 new tests passed on Linux and in an x86_64 QEMU/KVM guest. - The guest regression run passed 276 tests, skipped 5 prerequisite-bound cases and failed none across 13 dunitest/gVisor binaries. - Non-x86 architecture runtime and dedicated FUSE/overlay integration tests were not run. Refs: #2186 Signed-off-by: longjin <longjin@dragonos.org> * style(mm): use div_ceil for the shmem page count Replace the handwritten rounded-up division in the eager shmem mapping path with usize::div_ceil. This preserves the page count and EOF checks while satisfying the manual_is_multiple_of lint enforced by make fmt. Validation: make fmt completed and kernel formatting/Clippy passed. Some existing user application directories lack fmt targets; their formatting steps cannot be treated as passing. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
b0c037e634 |
fix(elf): preserve file backing for writable load segments (#2264)
* fix(elf): preserve file backing for writable load segments Writable PT_LOAD segments were copied into anonymous mappings. When a standalone Bun executable discarded its embedded source with MADV_DONTNEED, subsequent faults returned zero-filled pages instead of reloading the executable, causing CodeBuddy to fail with a NUL syntax error. Map executable and interpreter file segments through the existing private file-mmap lifecycle. Remove the duplicate eager mapping interface, reserve the image only for the first PT_LOAD, and preserve anonymous BSS handling. Keep explicit population for architectures without user page faults and handle short reads and protected user-copy failures. Use a single unevictable shmem page cache for RamFS file contents so lazy ELF faults preserve RamFS execution and buffered/shared/private mapping semantics. Serialize size changes and retain truncate invalidation and fallocate allocation behavior. Allow user buffers within the final partial file page while rejecting pages beyond EOF. Initialize CR0.WP during x86 AP startup: removing eager ELF copies exposed reliance on their incidental write-protection enable. Add 13 dunitest cases covering ELF discard/refault, private writes, fork, BSS, EOF buffers, and RamFS execution and data consistency. Validation: - make kernel; RISC-V and LoongArch kernel compile checks - New regression suite: 13/13 on Linux and DragonOS - DragonOS focused regression suites: 48/48 total - Identical CodeBuddy 2.147.0 binary: pre-fix NUL syntax error and exit 1; post-fix default startup reports version and exits 0 - Both x86 CPUs have CR0.WP enabled; exec ABI and clear_child_tid pass - Targeted rustfmt and git diff --check Cross-architecture guest execution, full initramfs boot, and the complete gVisor suite were not run. Signed-off-by: longjin <longjin@dragonos.org> * fix(ramfs): roll back failed page preallocation RamFS fallocate published each new unevictable page before the entire allocation completed. An intermediate ENOMEM left pages beyond the old EOF resident even though inode size and metadata were not committed. Extract the existing tmpfs preallocation loop into PageCacheManager and reuse it from both filesystems. Track only newly created page identities, reserve rollback metadata fallibly, and discard transaction-private pages on failure through the existing lifecycle helper. Retain pages acquired, mapped or dirtied by other users and publish inode metadata only after successful allocation. Keep tmpfs quota admission in the filesystem. Extend the accounting selftest with an isolated backend that fails page admission with ENOMEM. Verify repeated partial failures do not accumulate pages, existing data and identity survive, dirty and pinned pages are protected, retry succeeds, and teardown releases accounting. Validation: - Original allocation loop fails the injected rollback check in DragonOS - make kernel, targeted rustfmt, and git diff --check pass - DragonOS accounting dunitest: 1/1, including the new rollback assertions - DragonOS fallocate semantics: 8/8; ELF/RamFS regression suite: 13/13 - Tmpfs ENOSPC/data/EOF preservation and retry check passes on Linux and DragonOS - Independent adversarial review found no remaining blocking issues Signed-off-by: longjin <longjin@dragonos.org> * fix(mm): roll back uncommitted page-cache write preparation Preparing a multi-page write could leave newly allocated pages in the cache when allocation or a later pre-publication check failed. For unevictable RamFS mappings, pages beyond unchanged EOF then remained resident without user-visible data being committed. Keep write preparation in a private owner shared by all four write entry points. Record creation status while acquiring the entry pin, reserve copy and lock vectors fallibly, and check range arithmetic before page creation. On failure, release pins before retiring only newly created, still-discardable pages through the existing lifecycle helper. Preserve existing, mapped, pinned and dirty pages. Disable cleanup after successful publication; do not attempt to undo already published user data. Extend the accounting selftest with isolated ENOMEM injection, rejection by before_dirty, failed retention admission for ordinary and single-page writes, data preservation, successful retry and balanced teardown. Validation: the original implementation fails write_prepare_rollback in DragonOS. make kernel, rustfmt and diff checks pass; updated accounting selftest passes in the guest. Independent adversarial review completed before commit with no remaining blocking issues. Signed-off-by: longjin <longjin@dragonos.org> * fix(ramfs): clear the EOF tail on every truncate Full-PR review found that same-size and growing ftruncate skipped page cache truncation, leaving shared mmap writes beyond the new EOF visible. Linux ramfs simple_setattr calls truncate_setsize, which always truncates the page cache after publishing the new size. Reuse the existing page-cache resize path unconditionally while keeping the RamFS size lock and releasing the inode mutex before MM operations. Add a regression covering same-size and growing truncation, preserving the first data byte while clearing the new EOF tail. Validation: the new test passes on Linux ramfs and fails both tail-byte assertions on the original DragonOS implementation. The fixed guest passes ELF/RamFS 14/14, accounting 1/1, fallocate 8/8 and truncate/COW 2/2 (25 total). Kernel build and formatting checks pass. Full-PR and final adversarial reviews found no remaining blocking issues. Signed-off-by: longjin <longjin@dragonos.org> * fix(exec): retain inode write exclusion for executable images File-backed executable pages must not be modified or truncated by another writer. Introduce a VFS inode-wide writer/deny owner returning ETXTBSY on conflicting admission. Reuse canonical alias coordinators as stable identity and retain the inode across ownership; single-edge pseudo inodes use canonical allocation identity. Registry locking never spans filesystem operations or object destruction. Writable regular File descriptions hold writer admission through final close, including dup, fork and mmap references. Truncate and O_RDONLY with O_TRUNC acquire temporary admission. No checks are added to write hot paths. ExecParam acquires temporary deny protection before reading binary headers. The main image transfers shared File/deny ownership to its address space; fork inherits it and last-user mm teardown releases it after unmapping, even when external proc-mem references remain. Script recursion releases the old loading protection and PT_INTERP protection remains temporary, rather than following its VMAs for their entire lifetime. Add seven synchronized regression tests for existing writable descriptions, running-image writes/truncate/hardlinks, fork and exec, shared mappings, failed loads, scripts and proc-mem lifetime. Before the fix four core exclusion tests fail in DragonOS; all seven pass on Linux and the fixed DragonOS kernel. Validation: make kernel, rustfmt and diff checks pass. DragonOS focused suites pass 43/43, including exec ABI, ELF/RamFS, fallocate, proc exec, dumpability and accounting. Full-PR and final adversarial reviews were completed before commit with no remaining blocking issues. Signed-off-by: longjin <longjin@dragonos.org> * test(ramfs): verify mapped bytes exposed by file growth Extend the EOF-tail regression to distinguish bytes newly covered by EOF from bytes remaining beyond it. Linux ramfs preserves earlier explicit shared-mmap writes in the newly exposed interval and clears only the tail past the new EOF. Verify this through both the mapping and pread. The added assertions pass on Linux ramfs and DragonOS without changing the production growth path. Linux ramfs does not implement fallocate, so its unsupported operation is not used as evidence for different growth rules. Signed-off-by: longjin <longjin@dragonos.org> * fix(ramfs): preallocate only the requested fallocate range The resize-backed fallocate helper discarded the starting offset. After RamFS became sparse, a small request near the end of a large hole could therefore allocate every page from zero to the request end as unevictable memory. Pass the original offset through the existing atomic filesystem callback alongside the checked end. RamFS now preallocates only intersecting pages, matching the range used by Linux shmem_fallocate. Reject empty requests before entering the callback and document its validated range contract. Keep the existing size serialization, rollback helper, metadata commit, and non-shrinking EOF behavior. Ext4 and FAT retain their resize fallback. Add a bounded regression through a real RamFS inode to the page-cache accounting selftest and require its result in dunitest. Cover sparse growth, unaligned ranges, existing data, repeated allocation, preserved EOF, and page-aligned extension across a hole. Validation: - The same guest regression failed before the fix at ramfs_fallocate_range. - make kernel, rustfmt --check, and git diff --check passed. - QEMU: accounting 1/1, fallocate 8/8, ELF/RamFS 14/14, and executable write protection 7/7 passed (30 tests total). - Independent full-PR review and final-diff adversarial review found no additional blocking issues. Signed-off-by: longjin <longjin@dragonos.org> * test(vfs): cover overlay executable write exclusion lifetime Add an actual overlay mount case alongside the executable write-access regressions. Verify ETXTBSY while the outer writable descriptor remains open, successful exec after closing it with a shared mapping still alive, and successful exec after unmapping. Linux 6.6.139 ovl_mmap replaces the VMA file with the backing file. Its writer count belongs to the real inode, while exec deny_write_access checks the outer overlay inode. Retaining an additional outer writer through the mapping would change that behavior. Keep the existing kernel semantics and record this distinction in an automated native mmap test. Reuse the executable fixture and add bounded overlay mount cleanup. Use native mmap/close so no library-held duplicate descriptor affects the lifetime being tested. Validation: - Static musl test compilation and git diff --check passed. - Linux 6.8 host: executable write-access suite passed 8/8, without skips. - DragonOS QEMU with the unchanged kernel: the same suite passed 8/8. - Independently checked the Linux 6.6.139 source paths, reviewed the full PR, and adversarially reviewed the final test change before commit. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
ecef888198 |
fix(process): release clear_child_tid in the correct address space (#2263)
Process exit attempted to clear the registered userspace TID before checking whether the mm had another user, and successful exec retained the old registration. This produced EFAULT warnings for invalid addresses, could write through an obsolete address in the new image, and omitted the wake when writing a read-only TID word failed. Share robust-list and clear-child-TID cleanup between exit and exec. Consume the registration once, skip NULL and single-user-mm accesses, and attempt the shared futex wake independently of the protected clear result, matching Linux 6.6.139 mm_release semantics. Keep all faultable accesses outside PCB locks and perform exec cleanup with the old mm installed through the existing address-space switch helper. Preserve the existing mmput and vfork completion points; consume the exit completion before waking it. Add eight dunitests covering private/shared mm exits, NULL cancellation, failed and successful exec, invalid mappings, and wake after a failed clear. The read-only wake case uses an explicit phase and proc task state to prove the waiter is blocked, without timing sleeps or requeue dependencies. Validation: - make kernel, rustfmt checks, and git diff --check passed on x86_64. - Linux: 8/8 new tests passed; read-only wake passed 100 repetitions. - DragonOS QEMU/KVM, 2 vCPUs: new tests improved from 5/8 to 8/8. - ExecAbi 9/9, SpawnExecPipeRace 3/3, and ExecDumpableSemantics 1/1 passed on both the baseline and fixed kernel. - A separate libc-free exec address-reuse probe changed from corrupting the new image's shared sentinel to preserving it. - No clear-tid EFAULT warnings occurred in the fixed regression run. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
27066965ac |
refactor(net): remove noisy debug log in rtnetlink attr parsing (#2262)
Drop an accidentally committed log::info!() call inside convert_one_from_raw_buf(), which spammed an unrelated length message on every netlink route attribute decode. Signed-off-by: longjin <longjin@DragonOS.org> |
||
|
|
3b2d876451 |
feat(epoll): implement Linux-compatible epoll_pwait2 (#2261)
* feat(epoll): implement Linux-compatible epoll_pwait2 Implement syscall 441 with the native __kernel_timespec ABI and share the wait engine with epoll_wait and epoll_pwait. Previously, valid raw calls returned ENOSYS, preventing native event loops from using epoll_pwait2. Convert relative timeouts into a single monotonic nanosecond deadline at the syscall boundary, saturating oversized values at KTIME_MAX. Preserve NULL infinite waits and zero-timeout polls. Use existing timers as wakeup sources and verify the deadline before reporting expiry, without resetting the timeout budget on spurious readiness. Parse all six epoll_pwait arguments, validate non-NULL signal-mask sizes, and share temporary-mask handling with epoll_pwait2. Restore the saved mask on success, timeout and ordinary errors; preserve deferred restoration for EINTR so signal delivery and sigreturn retain the original mask. Check pending signals before expired nonzero deadlines, including 1 ns waits. Replace direct user-buffer slices with protected per-field event writes. Use the native epoll_event layout on each architecture without exposing padding. Preserve unsent entries after faults or maxevents truncation, return partial progress, and consume ET/ONESHOT state only after delivery. Requeue unprocessed entries ahead of delivered LT entries for fairness. Correct sigpending to intersect pending signals with the blocked mask, as required by Linux and exposed by the pending-signal regression test. Add 13 dunitest cases and register them in whitelist/no_skip. Cover timeout bounds, infinite and huge waits, errno ordering, six-argument ABI, temporary masks, SIGKILL/SIGSTOP, EINTR, protected writes and ready-list preservation. Validation: - Reproduced ENOSYS with raw syscall 441 on the unmodified SMP guest. - make kernel and formatting/diff checks passed. - All 13 new tests passed on Linux and a 4-vCPU x86_64 DragonOS guest. - All 21 gVisor epoll tests passed, including EpollPwait2Timeout. - All 11 existing epoll/poll/eventfd regression cases passed in the guest. Cross-architecture guest execution and CodeBuddy startup were not tested. Fixes #2238 Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
747eec23e4 |
fix(net): implement Linux-compatible transmit queue length queries (#2259)
BusyBox ip address reports SIOCGIFTXQLEN as unimplemented for every interface. The netdevice sysfs attribute also has no read implementation, and rtnetlink link messages omit IFLA_TXQLEN. Store an immutable tx_queue_len property in IfaceCommon with the Linux 6.6 default of 1000, including loopback and virtio-net. Read the same property from the generic socket ioctl query path, rtnetlink link message construction, and the read-only sysfs attribute. Reuse existing ifreq copying, name normalization, socket namespace lookup, and integer encoding so queries remain unprivileged, preserve unrelated union bytes, and return ENODEV or EFAULT through the established paths. Remove the sysfs attribute's unimplemented store override. Keep hardware descriptor counts, packet processing, and queue reconfiguration unchanged. Extend existing dunitest suites with queue-length ABI, alias, socket-family, capability, namespace, DOWN-interface, and user-copy fault coverage. Check that link dumps, individual link queries, ioctl, and sysfs agree even for interfaces without IPv4 configuration. Validation: - make kernel and Rust formatting checks passed. - Linux host: 8 ioctl query tests and 1 cross-interface consistency test passed. - DragonOS x86_64 QEMU: 8 ioctl query, 11 rtnetlink link, and 9 ioctl mutation tests passed with no skips after satisfying the existing IPv4 enumeration fixture prerequisite. - BusyBox ip address reports qlen 1000 for loopback and virtio-net without the previous warning, including an unconfigured virtio-net interface. Fixes #2258 Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
3ce437ee2d |
feat(rootfs): deterministic sysconfig payload for disk images (#2260)
- Introduce tools/build_sysconfig_payload.py, which renders a deterministic bin/sysconfig.tar from user/sysconfig-metadata.toml with numeric owner/group, explicit modes and a fixed mtime, so the payload no longer leaks host UID/GID/umask into the image. - Replace the copy_sysconfig step (cp -r of the sysconfig tree into bin/sysroot) with prepare_sysconfig_payload, and bump the sysroot layout version so stale files left by the old copy step are never imported again as app files. - Import the payload last in tools/write_disk_image.sh, extract with --numeric-owner/--preserve-permissions, then audit every member's type/uid/gid/mode against the tar headers; delete the image and rebuild when the payload schema version changes. - Add a CI job that runs the payload generator's unit tests. Signed-off-by: longjin <longjin@DragonOS.org> |
||
|
|
56fb0d67d1 |
feat(net): add namespace-aware netdevice sysfs projection (#2257)
* feat(net): add namespace-aware netdevice sysfs projection Give netdevices in every network namespace a real kobject and sysfs lifecycle. Tag direct net class children with their owning namespace and bind each sysfs mount view to the mount-time namespace and owning user namespace. Extend kernfs with namespace-keyed child buckets and allocation-free identity-preserving rename transactions. Route all VFS lookup and enumeration entry points through the filesystem view so same-named interfaces remain isolated without global scans or temporary lookup allocations. Unify fresh namespace device registration, deliver uevents to the device owner, and defer final namespace device teardown to a dedicated workqueue to avoid NAPI self-wait. Return ENODEV for stale weak sysfs callbacks and roll back partially published class glue objects. Expand rtnetlink dunitest coverage for mounted namespace projections, inode-preserving rename, stale attribute descriptors, and owner-namespace move events. Signed-off-by: longjin <longjin@dragonos.org> * fix(net): harden namespace sysfs teardown Keep links inside tagged netdevice directories relative to the shared sysfs hierarchy so alternate namespace-bound mounts cannot escape to the boot /sys view. Replace the workqueue VecDeque with an intrusive pending list and preallocate each network namespace cleanup work item and payload slot during construction. Final netns release can now transfer devices and enqueue teardown without allocating or risking an allocator panic. Extend the namespace sysfs regression test to follow the per-device subsystem link after rename and verify it resolves to the same device inode through the alternate mount. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
502fb750f4 |
refactor(net): unify link mutations across rtnetlink and ioctl (#2256)
* refactor(net): unify link mutations across rtnetlink and ioctl Centralize link name, MTU, and configurable flag changes in an ABI-independent RTNL transaction shared by RTM_SETLINK and legacy socket ioctls. Add Linux-compatible validation and namespace capability ordering, identity-preserving sysfs rename, runtime MTU and NOARP projection, and coherent route, neighbor, and link notifications. Model administrative link transitions with reversible NAPI pause and driver lifecycle hooks so DOWN waits for in-flight data-plane work without conflating it with permanent teardown. Preserve device-specific VirtIO and E1000 receive semantics. Add dunitest coverage for transaction rollback, name and flag semantics, namespace ownership, ioctl mutation, AF_PACKET down behavior, sysfs identity, and uevent delivery. Signed-off-by: longjin <longjin@dragonos.org> * fix(net): enforce packet transmit lifecycle and MTU Validate AF_PACKET sends against the selected interface's runtime MTU before and after copying user data. Preserve the selected interface across the copy, apply Linux-compatible Ethernet 802.1Q length handling, and share the path across send, sendto, and sendmsg. Add a netdevice-core TX admission gate so administrative DOWN is linearized with raw driver submission instead of relying on a racy flag check. Keep fresh namespace loopback devices Linux-compatible by bringing lo up in the gVisor runner after unshare. Cover RAW and DGRAM MTU boundaries, VLAN device-type rules, scatter-gather sendmsg, and DOWN error ordering in dunitest. Signed-off-by: longjin <longjin@dragonos.org> * fix(net): defer constructor routes until link up Do not publish address-derived FIB entries when a device is registered administratively down. Keep bootstrap routes independent, and let the first link-up transaction materialize every missing derived route while preserving idempotent notifications on later transitions. Extend the fresh network namespace loopback test to verify Linux-compatible IPv4 and IPv6 route visibility, local send behavior, broadcast withdrawal, and route restoration across down/up transitions. Signed-off-by: longjin <longjin@dragonos.org> * fix(net): support the Linux loopback MTU Expose the standard 64 KiB loopback MTU through both ioctl and rtnetlink while expanding the software loopback packet limit to match. Keep the configured MTU as the sole authoritative value and project it into smoltcp through an interface hook. Loopback caps that projection at the IPv4 16-bit total-length limit, avoiding malformed native IPv4 packets without introducing a second mutable MTU state. Add dunitest coverage for the fresh-network-namespace default and for 65535-to-65536 transitions through both control-plane APIs. Signed-off-by: longjin <longjin@dragonos.org> * fix(net): align poll retries and loopback MTU semantics Replace recursive interface poll revalidation with fixed-frame retry loops so sustained administrative state churn cannot exhaust the kernel stack. Preserve authoritative routing upgrades across retries and release all snapshot guards before restarting. Separate loopback's Linux-visible MTU range from smoltcp's protocol-safe projection. Apply low-MTU address teardown, FIB/source reconciliation, rename metadata, link state, and notifications as one prepared control-plane transaction. Revalidate every IPv4 UDP send against the current FIB and enforce the configured MTU at routed and loopback submission boundaries. Match Linux IPv4 lifecycle semantics by rejecting new published IPv4 addresses with ENOBUFS while MTU is below 68. Extend rtnetlink and ioctl dunit coverage for low MTUs, rollback, address/FIB withdrawal, fixed-source and broadcast sends, and recovery. Signed-off-by: longjin <longjin@dragonos.org> * fix(net): restore IPv4 loopback send semantics Centralize IPv4 loopback-subnet locality and broadcast classification in the address authority so bind placement, source validation, and candidate address transactions use one policy. Keep receive-side multicast and broadcast bind addresses separate from transmit source constraints, matching Linux inet_bind_sk behavior and allowing the route to select a valid unicast source. This restores the gVisor unbound UDP loopback and directed-broadcast cases while preserving stale-source rejection after low-MTU address withdrawal. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
972c818ba7 |
docs: migrate the documentation site from Sphinx to VitePress (#2255)
Keep English and Chinese as first-class locales, store frozen historical versions in the repository, and remove the machine-translation pipeline. Signed-off-by: longjin <longjin@DragonOS.org> |
||
|
|
9efb85e761 |
refactor(net): centralize rtnetlink neighbor state (#2253)
* refactor(net): centralize rtnetlink neighbor state Introduce a per-network-namespace authoritative neighbor table and split neighbor responsibilities into focused Rust modules. Keep control-plane existence distinct from Ethernet data-plane eligibility so headerless devices and non-Ethernet addresses retain correct netlink lifecycle semantics without creating synthetic MAC mappings. Align RTM_NEWNEIGH, RTM_DELNEIGH, and RTM_GETNEIGH parsing, mutation, dump, notification, and error ordering with Linux 6.6 behavior. Route IPv4 configured-neighbor output through a read-only policy view, serialize deletion with targeted smoltcp cache invalidation, and preserve lock ordering across deferred output restarts. Update smoltcp to the merged targeted invalidation API and add QEMU dunitest coverage for lifecycle flags, strict validation, notifications, namespaces, procfs projection, control-only entries, and real Ethernet destination selection. Signed-off-by: longjin <longjin@dragonos.org> * fix(tests): make neighbor UAPI checks host-independent Use test-local Linux 6.6 wire ABI values for neighbor attributes and extended flags that are absent from older build-runner headers. This keeps the netlink serialization coverage independent of the host UAPI package without introducing a repository-wide compatibility layer. Add regression coverage proving that fresh ordinary Ethernet PERMANENT and NOARP neighbors require a link-layer address, matching Linux __neigh_update semantics. Signed-off-by: longjin <longjin@dragonos.org> * fix(net): support neighbor master dump filters Normalize NDA_MASTER into Linux-compatible any, nomaster, and exact-master filter states. Since DragonOS does not yet expose a Linux-visible master/upper topology, nomaster selects current configured neighbors while exact master queries complete successfully with an empty dump instead of returning EOPNOTSUPP. Keep filter matching and NLM_F_DUMP_FILTERED decisions in one object, preserve whole-filter fallback for malformed non-strict requests, and replace the dunitest dump helper positionals with an options object. Cover exact, nomaster, zero, and malformed master selectors. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
6d16d6f4ff |
refactor(net): make route state authoritative (#2250)
refactor(net): make route state authoritative Implement the network control-plane architecture tracked by #2233. - Add an authoritative per-netns FIB and indexed longest-prefix lookup. - Make rtnetlink route, address, and link operations transactional. - Synchronize socket routing, software forwarding, and smoltcp projections. - Preserve Linux-compatible transport ownership, ingress identity, and TX backpressure behavior. - Harden namespace publication, TCP registration, PCI BAR resources, and scheduler deadline handling against races and allocation failures. - Add focused rtnetlink, networking, scheduler, and scalability coverage. Refs: #2233 Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
1e16411e73 |
feat(sched): implement sched_setparam semantics (#2252)
* feat(sched): implement sched_setparam semantics Add the sched_setparam syscall with Linux-compatible validation, error ordering, ownership, capability, and RLIMIT_RTPRIO checks. Route parameter-only scheduler updates through the existing queue transaction while preserving policy, reset-on-fork state, and RR slice state. Retry validation when a concurrent policy change invalidates the prepared update. Extend scheduler dunitests for ABI boundaries, permission rules, policy preservation, no-op queue ordering, remote running tasks, and concurrent FIFO/RR policy transitions. Signed-off-by: longjin <longjin@dragonos.org> * fix(sched): revalidate setparam priority at commit Carry the RT priority observed during sched_setparam authorization into the scheduler transaction and reject the prepared update when either policy or priority changed before the runqueue-locked commit point. This closes the stale-authorization window where a concurrent lowering could be followed by an unprivileged raise based on the older priority. Add concurrent writers coverage for the zero-RLIMIT_RTPRIO case. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
907ed50658 |
feat(sched): implement SCHED_RR timeslicing (#2251)
* feat(sched): implement SCHED_RR timeslicing Expose SCHED_RR through the legacy scheduler ABI with Linux-compatible realtime priority validation, permission checks, policy reporting, reset-on-fork behavior, and procfs labeling. Track the remaining round-robin quantum per task and rotate an expired task only when another runnable peer exists at the same realtime priority. Preserve the shared realtime runqueue, FIFO ordering, runtime bandwidth accounting, and migration model without introducing a parallel scheduler path. Keep policy-only and reset-only updates aligned with Linux queue placement semantics, including full FIFO/RR transitions and an in-place reset-on-fork flag update when policy and priority are unchanged. Extend scheduler semantics coverage for RR round trips, bounds, fork behavior, authorization, FIFO/RR transitions, equal- and mixed-policy ordering, blocking and wakeup, throttling, remote runqueues, and CPU affinity migration. Signed-off-by: longjin <longjin@dragonos.org> * fix(sched): expose the RR interval query Register sched_rr_get_interval on every supported 64-bit architecture and return the configured SCHED_RR quantum as a Linux-compatible timespec. Preserve zero intervals for FIFO and the currently sub-jiffy Fair slice. Resolve the target before validating the userspace output buffer so negative IDs, missing TIDs, and invalid pointers follow Linux error ordering. Snapshot the policy under the existing scheduler task lock without touching the mutable remaining quantum or taking a runqueue lock. Add dunitest coverage for raw and libc entry points, policy-specific intervals, other TIDs, invalid IDs, missing targets, bad pointers, and the exact 100 ms RR quantum. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
1bb5ca6453 |
feat(sched): expose Linux-compatible SCHED_FIFO to userspace (#2249)
Allow sched_setscheduler(2) callers to select SCHED_FIFO with the Linux priority range and permission model. Convert userspace priorities through the shared RT mapping and commit policy, priority, queue placement, and reset-on-fork state through the existing scheduler transaction. Share resource limits across CLONE_THREAD tasks while preserving fork snapshots. Serialize hard-limit authorization and replacement, return coherent prlimit64 old values, and keep RLIMIT_NOFILE table resizing as a lock-safe best-effort optimization. Enforce CAP_SYS_RESOURCE in the initial user namespace so nested namespace capabilities cannot raise the realtime hard limit. Extend scheduler semantics coverage for FIFO round trips, reset-on-fork, owner and target-limit authorization, thread-group limit sharing, concurrent hard-limit updates, nested user namespaces, yield ordering, runtime throttling, and remote policy-change preemption. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
6685c4672b |
feat(sched): enforce realtime runtime bandwidth (#2248)
Add per-CPU realtime bandwidth accounting with Linux-compatible default period and runtime limits. Track elapsed RT execution under the runqueue lock, throttle exhausted RT queues, and restore their eligibility after period replenishment. Integrate bandwidth updates into task selection, scheduler ticks, RT enqueue transitions, and class switch lifecycle. Keep throttled tasks queued locally while excluding them from the top-level runnable count and preemption decisions. Extend the FIFO scheduler demo with a deterministic Fair observer scenario that verifies both throttling and tick-driven RT recovery on each exercised CPU. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
d6684b6f63 |
refactor(net): move boot DHCP policy to userspace (#2247)
* refactor(net): move boot DHCP policy to userspace Complete the issue #2233 control-plane cutover by removing the kernel DHCP boot worker and selecting the primary Ethernet interface from userspace. Add an explicit default policy, fail-closed per-interface override selection, committed DHCP policy ownership, and regular-file resolver regeneration suitable for both ext4 and the default FAT root filesystem. Keep lease application transactional under the per-interface state lock, including active-policy validation, and schedule virtio NAPI after raw packet transmission so userspace DHCP receives immediate replies without polling unrelated drivers. Preserve rtnetlink as the single address mutation path and remove the kernel-only DHCP ownership APIs that are no longer reachable. Validated with make fmt, make kernel, shell syntax checks, Linux namespace integration including DHCP renew and policy races, default FAT image boot in QEMU, no-server boot, static and unmanaged transitions. Signed-off-by: longjin <longjin@dragonos.org> * fix(net): validate network configuration ancestors Reject network policy loads when any Unix-mode directory in the path from the root through the containing configuration directory is writable by group or other. Reuse the existing filesystem-aware directory validator so the default FAT rootfs keeps its verified synthesized-mode exception while ext4 policy paths become resistant to ancestor replacement races. Update the shipped operator documentation for automatic boot policy selection, explicit-policy precedence, resolver ownership, the FAT permission boundary, and the public command surface. Validated with a pre/post writable-ancestor chroot reproducer, the full host DHCP integration matrix, make fmt and clippy, a complete default FAT image build and QEMU DHCP boot, and a fresh three-role adversarial review. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
43f4d72808 |
refactor(sched): make scheduler changes atomic (#2246)
* refactor(sched): make scheduler changes atomic Introduce a single scheduler-change transaction that holds the task PI lock and a stable runqueue lock while updating policy, class, priority, queue placement, and reset-on-fork state. Preserve Linux 6.6 scheduler semantics by aging and transferring Fair PELT accounting across class changes, removing dead-task contributions, honoring realtime head placement on priority drops, and requesting the required local or remote reschedule. Centralize affinity publication under the same PI-lock boundary and make IRQ-time cross-CPU reads sound with atomic totals plus owner-local accounting. Extend the bounded fifo_demo coverage for remote queued and running tasks, realtime ordering, policy-affinity publication and migration, policy-exit races, cleanup results, and 1/2/3-CPU behavior. Validation: - make fmt ARCH=x86_64 (including all-features clippy) - x86_64 default and fifo_demo kernel builds - x86_64 fifo_demo boots with 1, 2, and 3 vCPUs - scheduler, affinity, tracepoint, process, and RCU dunitests - loongarch64 kernel build - riscv64 kernel compile, link, and ELF generation Signed-off-by: longjin <longjin@dragonos.org> * fix(sched): preserve migration state through switch tail Keep running tasks marked as migrating from source runqueue dequeue until the context-switch tail owns the task PI lock. This prevents concurrent scheduler class changes from accounting against a stale source runqueue. Make scheduler changes wait for the migration owner without contending on the PI lock, mirroring Linux task_rq_lock semantics. The switch tail now clears the transient state only while committing the destination enqueue or a completed stop, so no migrating state leaks past the transaction. Signed-off-by: longjin <longjin@dragonos.org> * fix(sched): migrate fair PELT accounting between runqueues Use the task-level migrating state to detach Fair PELT contributions from the source runqueue and reset the entity timestamp before rebinding it. Preserve ENQUEUE_MIGRATED through destination activation so the contribution is attached before the task becomes queued. Handle queued, current, and sleeping Fair migrations under the appropriate runqueue locks, and restore the source attachment when an asynchronous stop cancels a current-task migration. Keep dormant realtime entities and new-task placement outside the Fair migration transaction. Extend the scheduler feature test with deterministic Fair and FIFO migrations and enforce the migrated Fair timestamp invariant before destination enqueue. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
564b3cb412 |
feat(user): add dormant userspace DHCP service (#2245)
Introduce an opt-in dragon-network control plane for DHCP, static, and externally managed interfaces without changing the default kernel DHCP owner. The service validates root-owned data-only configuration, serializes per-interface control and lease mutations, records crash-recoverable network transactions, preserves external address and route ownership, and derives managed DNS atomically under /run. Add bounded and identity-checked udhcpc lifecycle handling, including DragonOS-compatible zombie detection, and mount /run as tmpfs during early userspace initialization. No interface configuration or startup hook is installed by default. Validated with make fmt, make kernel, make user, isolated Linux network namespaces using BusyBox, fault-injected transaction and route-ownership scenarios, and DragonOS QEMU boot plus DHCP lifecycle smoke tests. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
c00c0cc51c |
refactor(net): centralize interface address mutations (#2243)
* refactor(net): centralize interface address mutations Introduce a typed, RTNL-protected address mutation core that commits interface addresses, connected routes, and the router compatibility projection under one smoltcp lock. Capacity failures now roll back without exposing partial state, and runtime callers can no longer bypass the centralized path. Route rtnetlink and the one-shot DHCP client through the core, preserve Linux 6.6 address identity and notification semantics, and keep construction-only initialization explicitly separated from published-interface mutations. Add focused dunitest coverage for duplicate, replace, delete, parser, invalid-address, multi-address data-plane, route ownership, and capacity rollback behavior. Signed-off-by: longjin <longjin@dragonos.org> * fix(net): preserve address and route ownership Track in-kernel address leases with opaque generations so DHCP cannot delete a userspace-recreated address after a cross-event ABA. Persist Linux IFA_LABEL metadata across dumps, notifications, deletes, replaces, and interface renames, including length and empty-label semantics. Share canonical smoltcp route projections across address and rtnetlink owners, retain them until the final logical owner disappears, and isolate DHCP default-route updates from userspace defaults. Extend dunitest coverage for both owner orders, full-table rollback and sharing, alias labels, canonical prefixes, same-subnet addresses, and failed route replacement atomicity. Signed-off-by: longjin <longjin@dragonos.org> * fix(net): align address label policies with Linux Preserve raw IFA_LABEL payloads until the address-family adapter can apply the matching Linux policy. Validate IPv4 labels before address and interface processing, retain explicit empty labels for deletion matching, and omit empty labels from rtnetlink output. Ignore IFA_LABEL for IPv6 requests and notifications as Linux does. Extend rtnetlink address semantics coverage for empty and malformed IPv4 labels, error priority, IPv6 ignored labels, and attribute presence in dumps and notifications. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
0210af8096 |
refactor(sched): unify realtime runqueue model (#2244)
Rename the FIFO-specific scheduler and per-CPU queue to represent the shared realtime scheduling class while preserving the currently supported FIFO policy behavior. Harden realtime queue invariants by validating internal priorities, deleting exactly one matching task, moving only queued tasks during yield, and checking bitmap, bucket, and running-count consistency in diagnostic builds. Replace the unbounded FIFO demo with a feature-gated per-CPU smoke test that deterministically covers same-priority yield ordering, blocking, wakeup, task exit, and remote CPU runqueues without leaving runnable realtime workers behind. Validation includes x86_64, riscv64, and loongarch64 kernel builds; one- and two-vCPU FIFO smoke tests; scheduler policy, affinity, tracepoint, fork/signal, and RCU dunitests. Refs: #760 Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
3466f18cf2 |
refactor(sched): separate policy from scheduler class (#2242)
Introduce explicit LinuxSchedPolicy and SchedClass types so the user-visible scheduling policy no longer doubles as the scheduler's runtime dispatch class. Store policy and effective class separately in ProcessSchedulerInfo, initialize idle tasks before publication, and dispatch scheduler operations, accounting, RCU idle detection, PELT, and migration by class. Preserve policy-based syscall and procfs behavior without pre-modeling unsupported policies. Remove redundant FIFO hot-path policy checks and obsolete policy branches. Extend dunitest coverage for idle/iowait accounting and the legacy proc status scheduler label. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
379d2fe381 |
test(net): cover AF_PACKET DHCP client socket semantics (#2240)
* test(net): cover AF_PACKET DHCP client socket semantics Add deterministic AF_PACKET coverage for the socket contract used by BusyBox udhcpc. Verify SOCK_DGRAM ETH_P_IP broadcast transmission, kernel-generated Ethernet headers, peer ingress decapsulation, sockaddr_ll metadata, and PACKET_AUXDATA fields on the built-in veth pair. Build valid DHCP-shaped IPv4/UDP packets with checksums so the tests exercise the same framing assumptions as the client without requiring a DHCP server or external network. Keep interface indices and MAC addresses dynamic and bound all receive loops by monotonic deadlines. Refs: #2233 Signed-off-by: longjin <longjin@dragonos.org> * test(net): validate complete AF_PACKET DHCP frame length Use MSG_TRUNC when observing the outgoing SOCK_DGRAM frame so recvfrom reports the complete on-wire packet length instead of the copied byte count. This prevents an oversized Ethernet frame from satisfying the exact-length assertion after silent buffer truncation. Bound DHCP transaction matching to the bytes actually copied into the receive buffer while retaining the full returned length for the final assertion. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
21b7405d4a |
feat(sched): add legacy scheduler priority queries (#2241)
Implement sched_get_priority_min and sched_get_priority_max with the Linux 6.6 policy matrix. Keep the policy-to-range mapping in the legacy scheduler ABI layer and derive the real-time upper bound from MAX_RT_PRIO. Decode the syscall argument as a signed 32-bit policy so raw syscall calls follow the Linux int ABI. Reject unknown policies and reset-on-fork flag combinations with EINVAL. Extend sched_policy_semantics dunitest coverage for every supported policy, invalid values, and nonzero high syscall argument bits. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
9f8eabca93 |
feat(sched): support reset-on-fork scheduler semantics (#2239)
* feat(sched): support reset-on-fork scheduler semantics Align the legacy sched_getparam and sched_getscheduler interfaces with Linux by using the four-byte kernel ABI, signed TID lookup, unrestricted query semantics, consistent policy snapshots, and strict RT priority conversion. Implement the SCHED_OTHER reset-on-fork fast path for sched_setscheduler with Linux-compatible validation ordering, owner and CAP_SYS_NICE checks, protected-flag clearing rules, and per-task fork and clone reset behavior. Keep unsupported class transitions explicit and outside the runqueue mutation path. Tighten the internal FIFO priority endpoint, update the virtio block worker priority, and add dunitest coverage for ABI boundaries, errno ordering, other-TID access, credentials, fork, clone, and task lifetime behavior. Signed-off-by: longjin <longjin@dragonos.org> * fix(net): reserve ifindex one for loopback Linux assigns interface index 1 to the loopback device in every network namespace. DragonOS allocated the root loopback index from a global counter shared with device initcalls, so link-order changes could place lo after enough test interfaces that a bounded SIOCGIFCONF result omitted it. Define the loopback index invariant once, construct loopback devices with that index, and start dynamic root-device allocation at 2. Remove the allocation-based loopback constructor and strengthen the ioctl dunitest to assert the Linux ABI value. This restores all 41 ioctl_test cases while preserving normal interface enumeration semantics. Signed-off-by: longjin <longjin@dragonos.org> * fix(net): avoid veth ingress MAC lock recursion AF_PACKET classifies unicast ingress while the smoltcp interface lock is already held. VethInterface::mac previously reacquired that lock, deadlocking the NAPI worker and every later user of the interface. Keep the immutable veth MAC address in the interface metadata and make mac() a lock-free read. Document the data-path locking contract and extend the SO_BINDTODEVICE regression to verify the interface remains usable after ingress processing. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
8c6f8a888e |
feat(net): implement SO_BINDTODEVICE for UDP sockets (#2237)
* feat(net): implement SO_BINDTODEVICE for UDP sockets Add a reusable ifindex-based socket device binding abstraction with Linux-compatible set/get, capability, rename, and device removal semantics. Reuse the same authoritative state for raw sockets without expanding raw data-path scope. Move UDP port ownership and demultiplexing into a network-namespace binding table. Account for bound-device overlap, dynamic SO_REUSEADDR, bind-time SO_REUSEPORT groups, and efficient per-port lookup and removal. Honor the selected device across bind, connect, send, multicast selection, socket migration, local delivery, and receive demultiplexing. Preserve queued datagrams while moving sockets between interface socket sets and release resources on failure paths. Add focused dunitest coverage for getsockopt behavior, invalid devices, loopback traffic, device-scoped port conflicts, dynamic reuse settings, and CAP_NET_RAW authorization. Refs: #2233 Signed-off-by: longjin <longjin@dragonos.org> * fix(net): enforce UDP bound-device isolation Prevent the UDP local-delivery fast path from crossing the interface selected by SO_BINDTODEVICE. Snapshot the effective delivery interface and source endpoint while the socket state is stable so disconnects and concurrent state changes cannot corrupt loopback metadata. Reserve ifindex 1 for loopback in the root namespace, matching Linux and keeping SIOCGIFCONF discovery deterministic when many interfaces are present. Add focused dunitest coverage for cross-interface isolation, wildcard source selection, and the loopback ifindex contract. Remove the PR-local interface transition gate and retain the pre-existing IP_MULTICAST_IF behavior. SO_BINDTODEVICE permanently places the UDP socket on its selected interface, so the gate was unnecessary for this feature and did not solve per-datagram egress for asynchronous NAPI devices. Signed-off-by: longjin <longjin@dragonos.org> * fix(page-cache): synchronize writeback budget selftest Wait for production asynchronous writeback to quiesce before the debug selftest claims the global batch budget. Reserve every slot while holding the retry queue lock so normal acquisition and retry registration cannot race the selftest setup.\n\nThis removes the test-ordering failure seen when page-cache accounting runs immediately after overlayfs activity, while leaving production scheduling unchanged. Signed-off-by: longjin <longjin@dragonos.org> * fix(net): serialize UDP interface placement updates Model the smoltcp UDP socket's interface placement as a per-socket read/write transaction. Ordinary unicast sends retain shared concurrency, while multicast interface moves and control or lifecycle updates use exclusive ownership.\n\nThis prevents a concurrent SO_BINDTODEVICE update, multicast-interface publish, close, disconnect, or socket recreation from being overwritten by a stale post-send interface restore. Connected destination changes also participate in the transaction so send classification remains coherent. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
f8239b1310 |
feat(time): support timerfd syscalls (#2231)
* feat(time): support timerfd syscalls Implement Linux 6.6-compatible timerfd_create, timerfd_settime, and timerfd_gettime for realtime, monotonic, boottime, and alarm clock domains. Add one-shot and periodic expiration accounting, relative and absolute deadlines, nonblocking and close-on-exec flags, poll/epoll readiness, realtime clock-change rebasing, CANCEL_ON_SET handling, and safe final-close cleanup. Integrate timerfd with VFS open-file flags and Linux noop_llseek/read semantics. Add focused dunitest coverage and enable the corresponding gVisor timerfd test target in the whitelist. Validated with make kernel, the timerfd dunitest in DragonOS QEMU, and related eventfd, poll, epoll, and timekeeping regression suites. Signed-off-by: longjin <longjin@dragonos.org> * fix(time): make timer rebasing scalable Replace the globally sorted timer vector with a BTreeMap keyed by the immutable expiration and stable timer address. This keeps activation and cancellation logarithmic, preserves independent timers with identical deadlines, and removes the self-referential Weak pointer from Timer. Add coverage for identical-deadline timerfd cancellation. Align dunitest startup monitoring with its configured startup budget, and raise the actively progressing gVisor suite budget to 55 minutes while retaining idle and job-level bounds. This avoids quadratic timerfd clock-change rebasing and fixes the two CI failures without changing timerfd disarm semantics or adding a test whitelist. Signed-off-by: longjin <longjin@dragonos.org> * fix(timerfd): linearize clock-set notifications Record a timekeeping clock-set epoch whenever the realtime offset actually changes. Capture realtime and the epoch atomically when arming an absolute realtime timerfd, then ignore delayed notifications for the epoch already observed by that configuration. This prevents a timerfd armed after a wall-clock update from being canceled or redundantly rebased by the update's late notification. The epoch also avoids offset-token ABA across consecutive clock changes while preserving existing cancellation consumption semantics. Signed-off-by: longjin <longjin@dragonos.org> * fix(vfs): preserve record readv fault semantics Defer iovec mapping and permission faults until the protected data copy, matching Linux import_iovec behavior. Route record-oriented readv calls through the existing direct-user read path one iovec at a time. This preserves legacy scalar-read segmentation while allowing timerfd and inotify to retain their consume-before-copy ordering. Publish ACCESS once at the vector syscall boundary and cover timerfd split and invalid-buffer behavior with dunitest. Signed-off-by: longjin <longjin@dragonos.org> * fix(timerfd): prune expired realtime registrations Remove expired non-cancel realtime timerfds during the first clock-change traversal so stale entries do not impose repeated O(N) scans. Re-register periodic timers before sampling the realtime epoch when lazy forwarding needs them again, while keeping CANCEL_ON_SET membership intact. Add realtime-absolute periodic regression coverage for lazy rearm and subsequent expiration. Signed-off-by: longjin <longjin@dragonos.org> * fix(vfs): preserve socket readv fault semantics Route socket readv through a vectored UserBuffer so the receive operation copies directly into the caller iovecs and reports only a committed socket read. Make AF_UNIX stream, TCP, and AF_VSOCK stream consumption transactional with protected user copies, while retaining Linux datagram-style consumption for AF_UNIX seqpacket faults. Wake blocked peer writers whenever a seqpacket record is consumed. Add Linux-compatible regressions for later-iovec faults, short reads, empty socket error ordering, TCP retention, and seqpacket record consumption. Signed-off-by: longjin <longjin@dragonos.org> * fix(net): preserve recvmsg stream data on faults Copy TCP, AF_UNIX stream, and AF_VSOCK stream recvmsg payloads through protected vectored user buffers before committing receive-queue consumption. Preserve TCP MSG_WAITALL, MSG_PEEK, and MSG_TRUNC behavior, retain AF_UNIX stream record metadata across partial receives, and report EFAULT for incomplete seqpacket scatter while keeping datagram consumption semantics. Extend socket vector regressions for TCP and Unix stream recvmsg faults, TCP WAITALL continuation, and seqpacket recvmsg faults. Signed-off-by: longjin <longjin@dragonos.org> * style(net): simplify recvmsg wake condition Signed-off-by: longjin <longjin@dragonos.org> * fix(net): retain partial TCP reads on later faults Preserve bytes copied by an earlier smoltcp receive iteration when a subsequent iteration fails. This matches Linux TCP short-read semantics and prevents an EFAULT from hiding already-consumed stream data after the receive ring wraps. Add a deterministic dunitest that wraps the TCP receive ring, faults the later iovec, and verifies both the returned prefix and the unread tail. Enable the suite in the dunitest whitelist. Signed-off-by: longjin <longjin@dragonos.org> * fix(net): reject partial datagram recvmsg copies Return EFAULT when a record-oriented recvmsg cannot copy the complete selected payload into userspace. Keep stream short-read behavior unchanged, preserve records for MSG_PEEK, and retain Linux-compatible consumption after non-peeking faults. Cover UDP and Unix datagram fault semantics for both consuming and peeking receives. Signed-off-by: longjin <longjin@dragonos.org> * test(net): isolate AF_PACKET receive traffic Create explicitly bound packet receivers with protocol zero so they cannot queue wildcard traffic before bind. Give the fanout test a dedicated experimental EtherType so delayed frames from earlier cases cannot enter before group membership is complete. Signed-off-by: longjin <longjin@dragonos.org> * fix(net): copy TCP receive data outside interface lock Serialize TCP receive transactions per socket and stage direct user-buffer reads through a bounded kernel buffer. This keeps faultable user copies out of the interface-wide SocketSet critical section while preserving copy-before-consume semantics across EFAULT and terminal TCP transitions.\n\nAdd a concurrent readv regression test to verify that two readers neither duplicate nor lose stream data during peek-and-commit transactions. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
094fa1b877 |
feat(net): support Linux network device query ioctls (#2236)
* feat(net): support Linux network device query ioctls Add a shared, query-only socket ioctl adapter for SIOCGIFINDEX, SIOCGIFFLAGS, SIOCGIFMTU, and SIOCGIFHWADDR. Resolve devices through the namespace captured by each socket so descriptors retain Linux sock_net() behavior across namespace changes. Move SIOCGIFCONF into the adapter, serialize its multi-device snapshot with RTNL, remove synthetic loopback ordering, and copy data after releasing the lock. Only write back ifc_len, matching Linux while avoiding structure-padding disclosure. Add host/DragonOS coverage for ABI field widths, aliases, user-copy faults, unprivileged access, socket namespace stability, and ifconf padding. Remove the AF_PACKET hardware-address fallbacks so the standard ioctl path is exercised directly. Part of #2233. Signed-off-by: longjin <longjin@dragonos.org> * fix(net): derive user-visible interface flags Derive IFF_RUNNING, IFF_LOWER_UP, and IFF_DORMANT from the interface lifecycle, operational, and carrier state instead of returning cached initialization flags. Keep administratively configured receive-mode flags separate from AF_PACKET reference-counted effective modes, and use one projection for SIOCGIFFLAGS and RTM_GETLINK. Synchronize the interface START state when RTM_NEWLINK changes IFF_UP. Add cross-ABI link state coverage and verify packet memberships update rtnetlink counters without changing configured PROMISC or ALLMULTI flags. Signed-off-by: longjin <longjin@dragonos.org> * test(packet): isolate fanout frames across runs Tag each fanout load-balancing test invocation with a process- and run-specific marker so delayed frames from earlier AF_PACKET traffic cannot be counted as current input. Continue checking the 8/8 distribution while also asserting that every current sequence is delivered exactly once, preserving coverage for broadcasts, duplicates, and drops. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
ffe0f367fa |
refactor(net): serialize network control mutations with RTNL (#2235)
Add a network-owned RTNL guard and use it to serialize rtnetlink handlers, DHCP lease commits, and AF_PACKET membership updates under one explicit control-plane boundary. Keep parsing, polling, packet registry rebuilding, and netlink response delivery outside the global lock. Make route replacement failure-atomic at fixed table capacity and add isolated dunitest coverage for concurrent mutations, same-key linearization, and ENOSPC rollback semantics. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
892017b5f2 |
fix(net): enforce capabilities for rtnetlink mutations (#2234)
* fix(net): enforce capabilities for rtnetlink mutations Capture immutable credentials when a netlink socket is opened and for each send operation. Carry explicit-destination metadata through the netlink datagram path so route authorization matches Linux opener and sender semantics. Authorize every non-GET message in the Linux RTM range against the user namespace owning the socket network namespace before parsing handlers or attributes. Return per-message EPERM acknowledgements without affecting GET requests or privileged control paths. Add dunitest coverage for mutation classes, GET dumps, opener and sender credentials, explicit destinations, user and network namespaces, unsupported RTM types, and batched requests. Signed-off-by: longjin <longjin@dragonos.org> * fix(net): handle empty rtnetlink payloads Match Linux 6.6 rtnetlink dispatch ordering by completing RTM requests with an empty payload before capability checks and message parsing. Emit a success acknowledgment only when NLM_F_ACK is requested while preserving EOPNOTSUPP precedence above RTM_MAX. Extend the rtnetlink permission regression suite to cover empty payloads for both implemented and unsupported mutation types. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
151864c204 |
feat(rcu): implement SRCU support (#2232)
* feat(rcu): implement SRCU support Add independent sleepable RCU domains with two-bank per-CPU reader accounting, grace-period progression, deferred callbacks, barriers, polling, and explicit lifecycle management. Integrate SRCU with notifier chains, reboot notifiers, and tracepoints so sleepable read-side callbacks and snapshot reclamation follow Linux-compatible lifetime rules. Extend RCU diagnostics and self-tests, add dunitest coverage, and document the architecture and correctness invariants in both Chinese and English. Validated with make fmt and make kernel. Signed-off-by: longjin <longjin@dragonos.org> * fix(rcu): reject unsafe SRCU wait contexts Reject synchronous SRCU waits and cleanup from any deferred SRCU callback. All domains share one executor, so waiting on a different domain from that executor deadlocks just like a same-domain wait. Make bounded task-side reader tracking fail closed after overflow so an untracked same-domain reader cannot bypass deadlock detection. Add runtime regression coverage for overflow and cross-domain callback waits, and document the shared-executor constraint. Validated with make fmt, make kernel, and the DragonOS rcu_selftest dunitest in QEMU. Signed-off-by: longjin <longjin@dragonos.org> * fix(rcu): harden SRCU reclamation ownership Keep user-owned notifier and tracepoint destructors outside publication locks by retaining external ownership across every fallible preparation path and reclaiming snapshots only after the corresponding grace period. Record perf tracepoint callbacks immediately after publication using pre-reserved capacity, before any fallible logging, so release can always find and unregister published BPF/JIT resources. Restrict raw SRCU callback and in-place cleanup contracts, and document the COW notifier update boundary in both Chinese and English design documents. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
d91156384c |
perf(smp): reduce maximum CPU count to 16 (#2227)
Lower the global per-CPU allocation ceiling to 16 for lightweight agent-oriented workloads. This reduces the static kernel footprint and the runtime memory reserved by scheduler, RCU, IRQ, TLB, and other per-CPU structures. Resize the x86_64 GDT TSS descriptor area to match the new limit. Keeping the assembly table synchronized with the Rust TSS table preserves the early-boot GDT size invariant. Validated with make kernel and a QEMU nographic boot to the DragonOS shell with two vCPUs. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
fd4d8fcd45 |
test(rcu): add reproducible regression validation (#2226)
* test(rcu): add reproducible regression validation Add deterministic Linux-style RCU grace-period, reader-handoff, and cross-thread Arc-slot regression coverage. Introduce an SMP torture harness with seeded logical decisions, concurrent readers and publishers, synchronous and callback reclamation, per-generation callback completion, and barrier-prefix validation. Expose bounded runs through debugfs and exercise fixed seeds through dunitest. Keep intrusive objects in a stable boxed slice and isolate worker lifecycle ownership. If callback ownership cannot be proven, quarantine storage and poison later runs instead of risking use-after-free. Validated with make fmt, x86_64 and RISC-V kernel builds, and the rcu_selftest_test and rcu_torture_test suites in x86_64 QEMU. Signed-off-by: longjin <longjin@dragonos.org> * test(rcu): handle uniprocessor selftest reports Accept the explicit no-remote-CPU skip only when sysconf reports a single online CPU. Continue requiring the SMP litmus to complete on multi-CPU guests so CPU discovery and remote-worker regressions cannot be hidden. Validated with make fmt and rcu_selftest_test in rebuilt one-CPU and two-CPU x86_64 QEMU guests; both configurations pass all five cases. Signed-off-by: longjin <longjin@dragonos.org> * test(rcu): support uniprocessor torture runs Validate the torture report CPU count against the runtime online topology while allowing the harness to retain one reader on uniprocessor guests. Keep the multi-reader requirement for SMP and preserve all reclamation, callback, barrier, and corruption checks in both configurations. Validated with make fmt and rcu_torture_test in rebuilt one-CPU and two-CPU x86_64 QEMU guests; both fixed seeds pass. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
bcf46ccaea |
fix(tty): implement TCXONC flow control (#2225)
* fix(tty): implement TCXONC flow control Implement the four TCXONC actions in N_TTY with job-control checks, committed termios snapshots, atomic output state transitions, and a driver xchar hook with a generic fallback. Teach serial8250 to pause ordinary output while prioritizing flow-control characters, keep TX interrupt decisions consistent across console and IRQ paths, and reset private flow state across the first-open/last-close lifecycle. Preserve PTY packet notifications and gate virtual-terminal writes on the shared stopped state. Add dunitest coverage for action validation, blocked-writer wakeups, custom and disabled control characters, output-postprocessing bypass, and idempotent PTY packet notifications. Validation: - make fmt - make kernel - tty_termios: 20/20 passed in DragonOS - tty_tcflush: 6/6 passed in DragonOS - tty_pty_hangup: 36/36 passed in DragonOS - Python Ctrl+C produced KeyboardInterrupt without a kernel panic Signed-off-by: longjin <longjin@dragonos.org> * fix(tty): address flow-control races Serialize the xchar fallback snapshot behind the TTY write lock and track external flow-control transitions. Restore a temporary stop only when no concurrent start or stop request superseded it, and issue deferred write readiness after dropping all re-entrant locks when a racing start observed the temporary running state. Match Linux tty_port_close_start semantics for serial8250 by discarding a TCO-stopped software TX queue before waiting for already-submitted hardware bytes. This prevents last close from waiting for the fixed 30-second close timeout on a queue that cannot drain. Add a DragonOS dunitest regression that queues serial output under TCOOFF and verifies last close completes promptly. Validation: - make fmt - make kernel - tty_termios: 21/21 passed in DragonOS - tty_tcflush: 6/6 passed in DragonOS - tty_pty_hangup: 36/36 passed in DragonOS - Python Ctrl+C twice produced KeyboardInterrupt without a kernel panic Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
6cbf2f4c30 |
fix(rcu): guarantee grace-period forward progress (#2224)
* fix(rcu): guarantee grace-period forward progress Track active grace-period progress with deterministic soft-request, reschedule-IPI, and stall-report deadlines. Healthy CPUs can now drive escalation without relying on CPU0 jiffies or a bound worker. Keep timer hardirq work allocation-free by handing worker wakeups to an RCU softirq and performing stall validation and diagnostics in worker context. Bound callback batches by count and elapsed time, expose read-only state and statistics, and make x86 cycle conversion overflow-safe. Add deterministic policy and candidate-validation coverage together with a two-CPU production-path escalation test, slow-callback coverage, and debugfs dunitests. The selftest report is owner-only and cached after its first serialized run. Validated with make kernel and the 2-vCPU QEMU rcu_selftest_test suite (5/5 passing). Signed-off-by: longjin <longjin@dragonos.org> * fix(rcu): gate IPI selftest by architecture support Expose the generic KickCpu capability from the SMP layer and skip the hardware-dependent escalation selftest when an architecture does not implement that IPI path. Deterministic policy and failure-accounting coverage remains active on every architecture. Bundle grace-period pump callbacks into a focused hook structure and use checked division for statistics so the follow-up passes the repository's clippy gate without suppressing lints. Validated with formatting checks, RISC-V and LoongArch64 cross-builds, an x86_64 kernel build, and the 2-vCPU RCU dunitest suite. Signed-off-by: longjin <longjin@dragonos.org> * fix(rcu): harden cross-cpu progress timing Normalize x86 sched clocks per CPU against the global tick epoch while preserving monotonic local progress across stalled ticks and CPU hotplug. Couple remote clock reads through corrected values instead of mixing TSC offsets. Replace runtime u128 time conversion with an overflow-safe 64-bit quotient/remainder calculation. Track cacheline-isolated receive-side KickCpu events and require both target-specific RCU submission and delivery in the production-path selftest. Add deterministic coverage for counter offsets, backward motion, wraparound, resumed ticks, and monotonic reset behavior. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
b6096d7bcc |
fix(rcu): move context trackers out of lazy state (#2223)
RcuState embedded the full per-CPU context tracker array. The spin::Once lazy initialization path consequently reserved about 17 KiB of kernel stack even after initialization, which could exhaust a 32 KiB task stack when reached through IRQ and softirq wakeup paths. Build the tracker array directly in heap storage and retain it as a fixed boxed slice. This preserves tracker indexing, alignment, lifetime, synchronization, and hotplug semantics while removing the CPU-count-sized object from the lazy state value. Validated with a release kernel build, RCU PR1/PR2/PR3/PR5 selftests, three cold-cache apt update runs, one cached update, and a 200-process execution stress run. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
c2ba5d209e |
refactor(rcu): segment callback queues per CPU (#2222)
* refactor(rcu): segment callback queues per CPU Replace the globally serialized callback tracker and FIFO with cache-line-aligned per-CPU queues split into done, wait, next-ready, and next segments. Keep raw callback admission allocation-free and restrict its shared work to the local queue plus a coalesced worker kick. Advance callback generations as whole segments, execute bounded round-robin batches outside RCU locks, and implement rcu_barrier() with per-CPU tail markers that cover queued and executing callbacks. Serialize barrier scans with CPU lifecycle migration while preserving the upstream participating-CPU state as the single hotplug authority. Add per-CPU callback queue debugfs snapshots and extend RCU selftests for segment transitions, migration, callback requeue, multi-batch floods, all-online-CPU admission, concurrent barriers, and the upstream CPU lifecycle protocol. Tests: make kernel Tests: make run-nographic (2 vCPUs) Tests: /opt/tests/dunitest/bin/normal/rcu_selftest_test (3/3 passed) Signed-off-by: longjin <longjin@dragonos.org> * docs(rcu): document segmented callback queues Explain the per-CPU four-segment callback model, grace-period advancement, bounded execution, barrier markers, CPU lifecycle migration, and concurrency invariants without coupling the design to issue history or implementation details. Add a matching English translation and register both documents in their respective RCU documentation indexes. Signed-off-by: longjin <longjin@dragonos.org> * docs(rcu): clarify callback lifecycle Update the Chinese and English RCU architecture overviews with the per-CPU segmented callback lifecycle, its ordering boundaries, and the distinction between grace-period waits and callback barriers. Keep the overview concise and link both languages to the detailed segmented callback queue design. Signed-off-by: longjin <longjin@dragonos.org> * style(rcu): format callback imports Signed-off-by: longjin <longjin@dragonos.org> * fix(rcu): hand off barriers when worker exits Wake barrier waiters unconditionally after publishing that the callback worker has stopped. This lets a barrier that observed the old worker state recheck its predicate and take over bounded inline execution instead of sleeping forever with queued markers. Drain a small per-CPU callback quantum before resuming round-robin selection. This avoids rescanning every possible CPU for each callback in a single-CPU backlog while preserving a strict fairness bound for other CPUs. Tests: make fmt Tests: make kernel Tests: make run-nographic Tests: dunitest normal/rcu_selftest (3/3 passed) Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
ea5d81fb1c |
feat(rcu): support CPU hotplug lifecycle (#2220)
* feat(rcu): support CPU hotplug lifecycle Track RCU participation independently from the generic online mask so incoming CPUs join only future grace-period snapshots and dying CPUs transfer active responsibilities before stopping. Bind the callback worker to its creation CPU, add per-CPU kthread affinity protection, and publish explicit SMP Dying and Dead transitions for the architecture stop path. Cover repeated and concurrent lifecycle transitions while preserving the intrusive callback queue semantics introduced on the latest master. Signed-off-by: longjin <longjin@dragonos.org> * fix(rcu): make CPU teardown non-failing Remove the runtime policy assertion from the target CPU's RCU dying hook so fatal StopCpu and reboot teardown cannot panic while the system is still marked Running. Publish terminal CPU state only after local interrupt sources are disabled, target only the CPUs captured by the reboot barrier, and preserve target-owned terminal states when AP bring-up races with shutdown. Publish per-CPU kthread creation flags before task visibility so userspace cannot race sched_setaffinity against the worker bootstrap. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
bc88ffc24d |
fix(net): prevent TCP self-connect shutdown deadlock (#2221)
Release TcpSocket inner read guards before invoking interface polling or event notification callbacks. Rust extends temporary guards in if-let expressions, so a concurrent shutdown writer could make a nested reader wait behind that writer while the writer waited for the outer reader. Snapshot owned interface references inside short critical sections and poll only after guard release. Apply the same locking invariant to receive, send, connect, and accept paths, keep self-connected sockets off smoltcp polling, and move self-connect send notification outside the guard. Add a bounded IPv4 and IPv6 regression test that validates concurrent reads, a complete 1 MiB transfer, SHUT_WR, payload integrity, and EOF delivery. Tests: make fmt; make kernel; make test-dunit DUNITEST_PATTERN=tcp_self_connect_semantics; tcp_socket_test 184/184; SelfConnectSendRecv IPv4 and IPv6 10000 iterations each; make test-syscall 128/128. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
f6f02096e3 |
refactor(rcu): make raw callback admission intrusive (#2217)
* refactor(rcu): make raw callback admission intrusive Replace the growable pending and ready callback queues with one global intrusive FIFO backed by RcuHead. Raw callback publication now performs bounded pointer and sequence updates under the IRQ-saving RCU lock without reserving container capacity. Detach callback metadata before invocation so embedded heads can be destroyed or requeued safely. Preserve FIFO, grace-period, exactly-once, and barrier sequencing through the existing callback tracker, while keeping allocating closure helpers explicitly separate from the raw path. Tighten worker progress and lifecycle handling, avoid unnecessary wakeups while a grace period is blocked, and add deterministic coverage for allocation failure, duplicate claims, IRQ-disabled admission, embedded destruction, callback requeue, and sequence wraparound. Validated with make fmt, make kernel, the QEMU debugfs RCU selftest, and the rcu_selftest dunitest. Closes #2212 Signed-off-by: longjin <longjin@dragonos.org> * fix(rcu): fail boot when callback worker creation fails Treat the RCU callback worker as required boot infrastructure. Continuing after kthread creation failure leaves intrusive callback heads and deferred closures queued without an asynchronous drainer, so their resources can remain retained indefinitely. Fail fast before the kernel continues initialization, while preserving the existing disabled, idempotent, successful-start, and shutdown paths. This avoids introducing retry state, fallback executors, or callback execution in unsafe contexts. Validated with make fmt, make kernel, a QEMU failure-injection boot, normal QEMU boot, two debugfs RCU selftest runs, and the rcu_selftest dunitest. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
1102f6c913 |
feat(rcu): add persistent CPU context tracking (#2218)
* feat(rcu): add persistent CPU context tracking Introduce a cacheline-aligned per-CPU context state machine for kernel, user, idle, IRQ, and NMI contexts. Track quiescent-state generations so grace periods can exclude CPUs already in extended quiescent states and credit CPUs that pass through one after a grace period starts. Wire the context boundaries into x86_64 and RISC-V entry, interrupt, idle, and user-return paths. Keep architecture code limited to paired transition hooks, preserve nested interrupt semantics with typed tokens, and retain the grace-period waiting mask as the source of truth. Add deterministic transition and grace-period selftests, debug-only misuse diagnostics, and a dedicated RCU architecture document covering the stable context, grace-period, callback, ordering, and integration principles. Validated with make fmt, make kernel, a RISC-V kernel link, and two consecutive 2/2 RCU dunitest passes in a two-vCPU x86_64 QEMU guest. Closes #2210 Signed-off-by: longjin <longjin@dragonos.org> * docs(rcu): add English architecture guide Add the English RCU chapter and architecture guide alongside the Chinese source documentation. Preserve the same subsystem structure, context model, grace-period proofs, callback lifecycle, integration principles, and design boundaries in both language trees. Link the new chapter from the English kernel documentation index and keep all diagrams and section ordering aligned with the source document. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
d227ec56d1 |
refactor(rcu): extract grace period state machine (#2216)
Replace the redundant grace-period fields with a small deterministic state machine that owns sequence advancement, request coalescing, waiting CPU snapshots, and wrap-safe completion checks. Track callback generations with wrap-safe tickets and serialize lock-free callback draining through a single owner so rcu_barrier cannot observe out-of-order completion. Keep the existing worker, queue layout, public APIs, and debug snapshot contract unchanged. Document the ordinary non-preemptible RCU contract in code, make read guards task-bound, and place full memory barriers only at GP start, real quiescent-state reports, GP completion, and synchronous return boundaries. Add deterministic coverage for nested requests, empty masks, consecutive grace periods, sequence wraparound, callback ticket wraparound, drainer ownership, and callbacks admitted during an active GP. Tests: - make fmt - make kernel - /opt/tests/dunitest/bin/normal/rcu_selftest_test (QEMU, twice) Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
1fb3b878e2 |
fix(waitqueue): prevent lockless empty checks from losing wakeups (#2207)
WaitQueue wake_one() and wake_all() used a lockless waiter count as a correctness-critical negative check. An unlocker could publish the condition, observe a stale zero count, and skip the wake while the waiter failed its condition recheck and went to sleep. Always acquire the queue lock before deciding whether a wake queue is empty. This puts waiter registration and wake selection in the same linearization domain, matching the locking contract used by the regular Linux waitqueue wake path. Keep is_empty() as an explicitly advisory snapshot. Add a DoubleEpollOneShot progress regression that exercises the AF_UNIX mutex and waitqueue path through two independent EPOLLONESHOT registrations. Use a no-progress watchdog and MSG_NOSIGNAL so failures terminate deterministically without adding periodic wakeups to the operation under test. Fixes: #2202 Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
b990f6b283 |
fix(signal): preserve fatal delivery during sibling exec (#2206)
Keep a later SIGKILL on the normal pending and wakeup path when the thread group is already exiting. This matches Linux complete_signal semantics and prevents the delivery from being consumed without making the signal observable. For the first fatal group-exit transition, snapshot the group before waking tasks and explicitly queue SIGKILL to the selected target. This keeps the selected PCB covered across a concurrent non-leader exec identity exchange while avoiding duplicate wakeups. The change leaves group-exec ownership, wait barriers, and identity handoff unchanged. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
f64a0d5633 |
feat(vfs): implement close_range syscall (#2200)
* feat(vfs): implement close_range syscall Add Linux-compatible close_range(2) handling for close, CLOEXEC, and UNSHARE operations with the expected u32 ABI and validation order. Introduce a fallible two-phase fd-table clone so allocation failures cannot mutate the shared table or trigger close side effects. Scan close ranges with bounded work, perform file finalization outside fd-table locks, preserve reserved descriptors, and retain the correct POSIX lock owner semantics. Add deterministic no-skip coverage for range validation, raw argument truncation, shared and private tables, sparse descriptors, lowered RLIMIT_NOFILE, next-fd reuse, and record-lock ownership. Validated with x86_64 kernel format/check/clippy/build, a RISC-V kernel check, host Linux tests, and DragonOS guest tests. Signed-off-by: longjin <longjin@dragonos.org> * fix(vfs): bound close_range clone population Separate the cloned fd-table layout size from the installed File population bound. Tail punch-hole clones now stop copying at the last descriptor that must be retained instead of cloning up to the minimum 1024-slot layout and then closing those files. This avoids redundant Arc clones, range scans, and observable flush_for_close callbacks while preserving the minimum table capacity, reserved-fd behavior, next_fd recomputation, and ordinary clone semantics. Add a focused clone-plan regression test for a 64-fd retained prefix in a 1024-slot layout. Validated with kernel format, check, clippy, make kernel, host close_range tests, and three independent adversarial reviews. Signed-off-by: longjin <longjin@dragonos.org> * fix(vfs): track fd table task ownership Separate files-table lifetime references from PCB attachment ownership so procfs, BPF, and in-flight syscall observers cannot be mistaken for CLONE_FILES users. Introduce a lightweight FileDescriptorTable identity with an atomic task-user count and an RAII FdTableAttachment for PCB slots. Route private replacement, CLONE_FILES sharing, exec, close_range, fork cleanup, and exit through the attachment lifecycle while keeping final table destruction outside basic and fd-table locks. Use coherent table-and-sharing snapshots for exec and close_range, preserve the fallible close_range clone transaction, and add a focused ownership regression test proving observer Arcs do not affect sharing decisions. Signed-off-by: longjin <longjin@dragonos.org> * fix(vfs): harden fd table unshare semantics Track task attachments independently from transient Arc observers so close_range and exec only unshare genuinely shared descriptor tables. Keep table lifetime ownership separate from task-sharing identity and preserve POSIX lock ownership for private tables. Reuse the fallible descriptor-table clone path across close_range, fork, and exec. Preserve the allocation-before-population transaction boundary, use conditional rescheduling during range scans, and keep old table teardown outside process and fdtable locks. Harden exec after the point of no return by preparing fallible signal state early and terminating through the normal fatal-exec path when later image installation fails. Add close_range ownership and exec isolation regression coverage. Signed-off-by: longjin <longjin@dragonos.org> * fix(exec): avoid synchronous RCU sighand reclamation Retire replaced sighand references outside task_lock through a fallible RCU callback admission path so shared-sighand exec no longer waits for a global grace period during normal operation. Reserve both pending and ready callback capacity before publication to keep grace-period advancement allocation-free. Preserve the removed Arc on allocation failure and use a no-allocation yielding grace-period fallback instead of turning post-PONR memory pressure into a kernel panic. Add RCU selftests for fallible deferred drop and no-allocation grace-period progress, plus deterministic successful and post-PONR shared-sighand exec isolation coverage. Validated with kernel build, formatting, nightly clippy, DragonOS guest exec ABI tests, and multi-agent adversarial review. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
60c7f860d3 |
feat(kernel): add SMP-safe text patching (#2203)
* feat(kernel): add SMP-safe text patching Introduce a transactional text patching core and an x86_64 backend that parks remote CPUs, validates expected instruction bytes, writes through dedicated RW+NX fixmap aliases, and synchronizes instruction fetch before returning. Vendor static-keys 0.8.2 with a minimal transactional backend interface so a key publishes its enabled state only after every branch site commits successfully. Migrate tracepoints to audited DragonOS declarations and propagate control-plane failures without adding work to the disabled fast path. Move perf event final release to a preallocated deferred worker so File::drop never sleeps or patches text. Quiesce patching during reboot and add single-CPU, SMP stable-epoch, tracepoint, and deferred-release coverage. RISC-V and LoongArch64 remain fail-closed until their SMP, IPI, and W^X prerequisites are implemented. Signed-off-by: longjin <longjin@dragonos.org> * doc: add text patching docs Signed-off-by: longjin <longjin@dragonos.org> * fix(kernel): address text patching regressions Preserve tracepoint enablement on architectures without a live text-patching backend by using the Linux-style dynamic-key fallback, while keeping x86 static branches unchanged. Validate all early-ioremap size and address arithmetic before slot allocation, publish static-key initialization with acquire/release ordering, and restore hosted dependencies required by workspace tests. Signed-off-by: longjin <longjin@dragonos.org> * fix(kernel): satisfy x86 text patching lints Use direct iteration for the text-poke alias table, remove a redundant perf-worker closure, and document the unsafe transaction queue contract. Signed-off-by: longjin <longjin@dragonos.org> * fix(perf): retry transient text patch timeouts Keep the release node and callbacks alive when an x86 text rendezvous times out before commit, then retry from the sleepable worker after a bounded backoff. Document the retry-safety contract for perf event implementations. Signed-off-by: longjin <longjin@dragonos.org> * fix(perf): requeue timed-out releases Return a timed-out release node to the existing intrusive queue after backoff so one unresponsive text-patch target cannot monopolize the global perf release worker. Signed-off-by: longjin <longjin@dragonos.org> * test(tracepoint): restore SMP test affinity Use an RAII guard to restore the gtest thread's original CPU mask on both normal completion and fatal assertion exits. Signed-off-by: longjin <longjin@dragonos.org> * fix(kernel): enforce strong text patch completion Use the calibrated TSC only for the boot-time rendezvous probe, then give live text updates stop-machine-style strong completion semantics. Remove deferred perf retry amplification and route executable-text invariant failures through a no-unwind machine stop. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
004bbebe81 |
fix(ext4): preserve delalloc cleanup across metadata contention (#2199)
* fix(ext4): preserve delalloc cleanup across metadata contention Treat empty delayed-allocation lease releases as true no-ops before entering the metadata mutation gate. Keep projected admission and local rollback in one direct-metadata ownership window, preserve capabilities across EAGAIN, and terminalize them safely after fail-stop. Linearize queue-empty cleanup by closing admission and detaching the pool under the inode I/O lock before retrying cancellation or release without inode locks held. Cover empty and non-empty gate contention, projected cancellation, healthy rollback, and concurrent fail-stop with deterministic lower-layer tests. Signed-off-by: longjin <longjin@dragonos.org> * fix(ext4): drain idle owners after cleanup failure Run the filesystem-wide idle delayed-allocation terminalizer only after the current cleanup bundle has released its registry owner and admission guard. Also sample an already-terminal metadata state so an empty no-op pool release cannot skip draining other Prepared or Ready owners after a concurrent fail-stop. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
b915f28ba7 |
fix(vfs): preserve poll timeout without wait sources (#2197)
PollAdapter treated an empty internal epoll registry as an immediate return even when no pollfd had produced revents. Arrays containing only ignored descriptors therefore bypassed their timeout, causing callers such as SpawnExecPipeRace to exhaust a nominal multi-second wait budget in milliseconds. Distinguish immediate results from the no-source state and route the latter through the existing timeout/signal wait path. Align the timeout-only path with Linux ready-before-signal-before-timeout ordering by checking pending signals before an expired deadline. Add deterministic poll and ppoll coverage for ignored descriptors, regular files with no requested events, POLLNVAL immediacy, and pending-signal precedence. Keep the suite in the mandatory dunitest set. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
f705cc12f0 |
fix(net): preserve TCP self-connect partial reads (#2196)
* fix(net): preserve TCP self-connect partial reads Keep self-connected receive probe errors inside the cumulative read loops so a later EAGAIN cannot discard bytes that were already copied and dequeued during the same syscall. Apply the same result propagation to direct user-buffer reads and kernel-buffer recv paths. Treat an exhausted receive-shutdown allowance as the current probe's EOF result instead of returning past previously accumulated progress. Add deterministic IPv4 and IPv6 regression coverage for read, recv, initial would-block behavior, and receive-shutdown partial progress. Enable the suite in the dunitest whitelist and require it to run without skips. Signed-off-by: longjin <longjin@dragonos.org> * test(gvisor): block failing dev tty case Block only BasicPtyTest.OpenDevTTY in pty_test because the forked child currently exits with status 1 on the master baseline. Keep all adjacent PTY coverage enabled so unrelated terminal behavior continues to run in integration CI. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
3baab8d70b |
test(net): cover IPv6 raw checksum optlen semantics (#2195)
Add non-skippable dunitest coverage for the Linux 6.6 IPV6_CHECKSUM length and user-access contract. Verify short lengths fail before touching optval, full-length inaccessible values return EFAULT, oversized lengths consume only the integer prefix, and rejected operations preserve the configured checksum offset. Exercise EBADF and ENOTSOCK precedence, use guarded mappings to make the EINVAL/EFAULT boundary deterministic, and keep resource cleanup local to the tests. Exclude only the stale gVisor ReadShort subtest, which expects Linux behavior from before fb7bc9204095, while retaining the rest of the raw socket suite. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
4da26c6bf5 |
fix(vfs): isolate page-cache writeback lifecycles (#2194)
* fix(vfs): isolate page-cache writeback lifecycles Replace the global page-cache ownership scan with per-filesystem writeback domains bound to a single superblock. Mount synchronization now enumerates only caches owned by that filesystem and routes writeback errors directly to the affected mapping and superblock errseq. Add explicit I/O admission, owner pinning, in-flight accounting, and shutdown draining for asynchronous reads, tagged writeback, reclaim, and ext4 delayed-allocation producers. Preserve accepted work across continuations while rejecting new work after shutdown, and retire dormant generations without fabricating writeback failures. Reorder final mount teardown so filesystem-private producers quiesce before domain closure, all admitted work drains before cache retirement, and filesystem state remains alive until completion. Make file-backed page-cache construction explicit for ext4, FAT, FUSE, and virtiofs, while keeping unowned caches opt-in. Strengthen mount and superblock identity handling, propagate binding failures instead of panicking, and add deterministic domain lifecycle self-tests covering admission, draining, owner retention, error isolation, and registry cleanup. Signed-off-by: longjin <longjin@dragonos.org> * refactor(vfs): clarify page-cache shutdown hook Rename the filesystem lifecycle callback from prepare_page_cache_retirement to quiesce_page_cache_producers. The new name describes the actual contract: filesystem-private producers must stop before the generic writeback domain is closed and its caches are retired. Keep the shutdown order and behavior unchanged across ext4, FUSE, virtiofs, and MountFS. Signed-off-by: longjin <longjin@dragonos.org> * refactor(vfs): satisfy writeback clippy checks Represent paired writeback indices with WritebackBatchRange so claim helpers stay within the clippy argument limit and make the contiguous-range contract explicit. Keep ClaimedWritebackBatch inline with a documented local large-enum exception. Boxing the batch would add a heap allocation to every real writeback operation and deepen the recursive PageCache/workqueue Send and Sync type graph. Apply rustfmt output to the touched writeback and ext4 paths. This change does not alter writeback ordering, admission, completion, or error publication semantics. Signed-off-by: longjin <longjin@dragonos.org> * fix(fuse): quiesce cached reads before cache retirement Track each FUSE page-cache READ with its filesystem writeback-domain permit until the request publishes or rolls back its Loading entries. This makes accepted read I/O visible to the domain drain and keeps the filesystem owner alive through terminal completion. During final FUSE shutdown, close new domain admission and cancel only the pending reads owned by that domain before generic cache retirement. This prevents speculative readahead requests from leaving Loading pages that make unmount wait forever, while preserving unrelated requests and shared-connection submounts. The cancellation path removes matching queued and processing requests under the connection lock, then completes them outside the lock so DMA reservations, open pins, background credits, and domain permits retire through the normal completion path. Signed-off-by: longjin <longjin@dragonos.org> * fix(tmpfs): route mapping errors through mount domain Register page-cache mappings created by mounted tmpfs instances with the filesystem writeback domain. This restores mapping_set_error semantics by advancing both the mapping errseq and the owning superblock errseq, allowing syncfs observers to report writeback failures. Add a filesystem-owned shmem PageCache constructor that preserves shmem accounting while binding the mapping to the same shutdown and error-routing domain used by disk-backed filesystems. Keep the internal SysV shmem tmpfs explicitly unowned so it does not require a mounted superblock or participate in mount teardown. This fixes the errseq_writeback_reporting CI regressions without restoring the global mount scan or conflating unmounted kernel shmem with mounted tmpfs lifecycle management. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
6aff128d71 |
fix(vfs): implement SEEK_DATA and SEEK_HOLE (#2192)
Decode the Linux SEEK_DATA and SEEK_HOLE whence values instead of treating SEEK_DATA as an end-of-file alias. Preserve Linux error precedence by resolving the file descriptor before validating whence. Implement the generic regular-file fallback in File::lseek: report offsets before EOF as data, report EOF as the virtual hole, return ENXIO at or beyond EOF, and leave the shared open-file-description offset unchanged on failure. Reuse one metadata snapshot and reject sparse-seek operations for unsupported file types and VecCursor. Add dunitest coverage for dense and empty files, boundary errors, shared offsets through dup, invalid descriptor precedence, and directory rejection. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
c435e93986 |
fix(exec): clean robust futex state before mm replacement (#2191)
Successful exec replaced the current address space while leaving the task's robust-list registration pointing into the old mm. A later task exit attempted to walk that stale userspace list, producing recoverable missing-VMA faults and skipping the required owner-death transition. Take robust-list ownership exactly once and reuse one cleanup core for exit and exec. During the successful exec commit, temporarily restore the old mm, perform best-effort owner-death cleanup, and switch back to the new mm. Keep failed exec paths unchanged. Align exec mm switching with the scheduler's active-CPU and TLB ordering. Replace raw userspace AtomicU32 operations with exception-table-protected cmpxchg implementations for x86_64, RISC-V, and LoongArch, including 32-bit sign-extension and weak LL/SC ordering requirements. Validate robust entries, preserve PI and pending metadata, use namespace-visible task IDs, and stop safely on malformed userspace state. Defer missing-VMA diagnostics until exception-table recovery fails so expected nofault accesses do not emit misleading errors. Add exec ABI coverage for owner-death cleanup, registration reset, deterministic read-only futex faults, and early and late exec failure preservation. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
567e2b119d |
fix(epoll): prevent hardirq registration deadlocks (#2188)
Encapsulate poll-source epoll registrations behind an IRQ-safe list API so task-context add and remove operations cannot be interrupted and re-enter the same spin lock from a device IRQ. Linearize callback publication with DEL, file release, and epoll close through an active registration state protected by the ready-state lock. Use open-file identity together with the descriptor as the registration key, remove socket registrations precisely, retain the signalfd registration owner, and clean up epoll sources using the registered file rather than the caller's descriptor table. Add bounded regressions for concurrent HVC TX completions, callback requeue after DEL, duplicated socket descriptors, and descriptor-number reuse. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
dace5e9e0e |
fix(ext4): implement atomic symbolic link creation (#2187)
* fix(ext4): implement atomic symbolic link creation Implement a filesystem-specific symlink creation path instead of relying on the generic create-and-write fallback, which published an empty inode before ext4 rejected the target write with EINVAL. Store fast symlink targets in the inode inline area and initialize longer targets in an extent-backed data block before publishing the directory entry. Preserve directory insertion failure classification so only provably unpublished inodes are reclaimed, while indeterminate metadata writes fail-stop the mount without reusing a potentially reachable inode. Harden unpublished inode rollback for inline and extent-backed representations, including the transient state where an extent tree is updated before i_blocks is recomputed. Add host fault-injection coverage and loop-ext4 tests for the 59/60-byte boundary, remount persistence, target fidelity, and resource reclamation. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
824d2574cc |
fix(mm): support shared /dev/zero mappings (#2185)
* fix(mm): support shared /dev/zero mappings Create an independent anonymous shared backing for each MAP_SHARED /dev/zero mmap while preserving that backing across fork and other derived VMAs. This matches Linux shmem-visible behavior without introducing a global inode page cache or a new shmem subsystem. Route faults and fault-around through the shared backing, publish newly allocated pages with a two-phase race-safe path, and teach futex, mincore, and msync to interpret hybrid file/shared-anonymous VMAs consistently. Keep fault-around lookup-only so sparse accesses do not allocate cold neighbor pages. Add dunitest coverage for lazy faults across fork, per-mmap isolation for same and different file descriptors, futex wakeups, mincore residency, msync, and sparse fault-around behavior. Fixes #2181 Signed-off-by: longjin <longjin@dragonos.org> * fix(mm): serialize shared page publication Keep the PageManager mutex across allocation and backing publication, and recheck the backing after acquiring it. Concurrent faults can now reuse a page published by the allocator lock holder instead of reporting a false ENOMEM while that page is still in flight. This also removes duplicate candidate allocation and cleanup without introducing per-index state or another sleeping lock. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
60b478306b |
perf(x86_64): accelerate logical CPU lookup (#2184)
* perf(x86_64): accelerate logical CPU lookup Replace the steady-state APIC MSR and CPUID based CPU lookup with a validated task-register selector decode. Extend the shared GDT so every supported CPU has a complete TSS descriptor, retain the bootstrap discovery fallback, and verify descriptor ownership before trusting the decoded logical ID. Keep VMX host state correct with per-CPU TR selectors by refreshing HOST_TR_SELECTOR and HOST_TR_BASE together. Add synchronized remote loaded-VMCS clearing, pin direct VMCS accesses against task migration, and snapshot exit information before returning to preemptible slow paths. Split MMU root preparation from EPTP submission so allocation remains preemptible while VMCS writes occur only after the current CPU and active VMCS are confirmed. This removes the dominant page-fault CPU-identification overhead without changing allocator zeroing semantics or adding workload-specific behavior. Validation: make kernel; RISC-V64 and LoongArch64 kernel checks; 2-vCPU QEMU boot; sched_affinity_test; page_fault_accounting_test; mlock_semantics_test; cargo fmt --check; git diff --check. Signed-off-by: longjin <longjin@dragonos.org> * fix(vmx): serialize active VMCS updates against IPIs Keep local interrupts disabled while updating the loaded-VMCS list and transitioning the per-CPU active VMCS. This prevents the remote-clear IPI from mutating current_vmcs through an exclusive reference while the ordinary load path still holds a shared reference. Complete any remote clear before entering the IRQ-disabled section, and publish the new owner only after the VMCS host state is initialized. The critical section therefore covers only per-CPU list and active-VMCS state without extending the synchronous remote-clear wait. Validation: cargo fmt --check; git diff --check; make kernel; three-role adversarial review covering concurrency, correctness, Linux semantics, lifecycle, and performance. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
03359a2454 |
test(procfs): fix TID reuse cache test semantics (#2179)
pthread_join only waits for CLONE_CHILD_CLEARTID completion and does not guarantee that the exiting TID has already been unhashed from procfs. Remove the immediate ENOENT assertion that depended on that unsupported ordering. Treat failure to observe TID reuse within the fixed construction budget as an unmet test precondition on every platform. The namespace open and readlink checks still execute while each replacement thread is alive, so a stale cached TID directory continues to fail whenever reuse is actually observed. Fixes #2174 Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
bb8207ac79 |
perf(mm): compact page-level reverse mappings (#2183)
Replace the per-page reverse-mapping HashSet with a private compact representation that stores the first two VMA references inline and upgrades to a sticky HashSet only when a third distinct VMA is attached. Move existing Arc references between Empty, One, Two, and Many states instead of cloning them during transitions. Allocate the Many representation before taking the inline state so allocation failure cannot discard existing reverse mappings, while preserving map counts, duplicate detection, mlock tracking, and final page reclamation semantics. Add a SysV shared-memory regression test that faults the same pages through three aliases, verifies coherence, and detaches each alias independently. This exercises inline insertion, HashSet promotion, sticky removal, and the final transition back to an empty reverse map. Validation includes x86_64 kernel builds, RISC-V and LoongArch64 checks, the full SysV shared-memory suite, page-fault, TLB-shootdown, mlock, and OOM regression suites, plus fork and VMA-split performance comparisons. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
4dc7f8e253 |
perf(mm): optimize anonymous page fault handling (#2182)
Remove the per-fault CPUID query from the x86 SMAP check and evaluate the active CR4 state only for supervisor faults. Align the access-flag condition with Linux semantics. Return newly allocated managed pages from PageMapper so anonymous and /dev/zero fault handlers can reuse the original Arc directly. This avoids redundant page-table translations and global page-manager lookups while preserving allocation failure cleanup. Reuse fault-time VMA snapshots, reject malformed shared-anonymous mappings, and prevent /dev/zero fault-around population from replacing existing leaf mappings. Add regression coverage for overlapping /dev/zero fault-around windows, MAP_POPULATE, shared-anonymous delayed faults across fork, and page-fault accounting. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
eda4b96964 |
feat(mm): account page faults through Linux-compatible APIs (#2180)
Track completed minor and major faults per task and expose the existing resource aggregation through getrusage and procfs. Distinguish thread-group and per-thread /proc stat views while preserving exited-thread and reaped-child accounting. Add cache-line-sharded system pgfault and pgmajfault counters. Record major events at the backing-I/O source, defer retry accounting until completion, and keep failed or interrupted waiter paths aligned with Linux 6.6 semantics without adding locks, allocation, CPU probing, or logging to the fault hot path. Add dunitest coverage for anonymous write faults, thread versus thread-group reporting, vmstat updates, and reaped-child aggregation. Validated with: - make kernel - cargo +nightly-2026-02-24 fmt --manifest-path kernel/Cargo.toml -- --check - page_fault_accounting dunitest on Linux and DragonOS QEMU - wait_rusage dunitest on DragonOS QEMU - git diff --check Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
5f1d437f85 |
fix(tty): support virtual consoles without framebuffer (#2178)
Select and cache the virtual terminal console backend when the first VT is installed. Use the framebuffer console when fb0 exists and the dummy console otherwise, while preserving one shared backend across all virtual consoles. Represent vcN as an identity-protected devfs symlink to ttyN so aliases do not register duplicate device numbers. Keep symlink creation and removal atomic under the devfs operation lock, including correct unlink metadata updates. Roll back automatically allocated TTY indexes when installation fails, preserve explicit index ownership, and keep default console selection available when tty0 creation reports an error. Add dunitest coverage for tty0 and vc0 device semantics in framebuffer-less boots. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
1715d828a3 |
refactor(ci): consolidate bug-hunter personas to 3 orthogonal roles (#2177)
Merge the previous 8-agent persona matrix into 3 orthogonal roles to cut token waste while keeping defect-class coverage: - Security & Concurrency Sentinel (weight 4.0): security + concurrency - Logic & Correctness Reviewer (weight 3.0): logic / boundary / error handling - System & Performance Reviewer (weight 3.0): performance + resource lifecycle + Linux semantic contracts Embed the persona matrix in weighted_vote.py (DEFAULT_WEIGHTS) and drop the external persona_matrix.json loading path. Update the stage 1/2/4 skill docs accordingly and add Python artifacts to .gitignore. Signed-off-by: longjin <longjin@DragonOS.org> |
||
|
|
974c9044ac |
ci: temporarily disable claude-review workflow job (#2176)
The claude-review bot is currently erroring in CI. Disable it for now and restore by removing the 'if: false' line. Signed-off-by: longjin <longjin@DragonOS.org> |
||
|
|
86d14be129 |
fix(ahci): integrate controller with PCI driver model (#2168)
* fix(ahci): integrate controller with PCI driver model Register AHCI controllers through the standard PCI driver lifecycle and distinguish absent controllers, empty ports, and genuine device failures. Preserve PCI command state and make controller, port, command-memory, and disk ownership explicit during probe, I/O, removal, and shutdown. Add bounded physical-page allocation for DMA masks, reject incompatible pooled buffers, and provide an on-demand debugfs self-test with deterministic buddy split, merge, fragmentation, and address-bound checks. Align block-device publication with Linux semantics by retaining the whole-disk node across partition scan or publication failures, preserving MBR slot numbers, and clipping partitions to device capacity. Add dunitest coverage for DMA allocation behavior and zero-capacity loop devices. The change has been validated with kernel builds, targeted dunitests, and QEMU AHCI matrices covering empty, valid-MBR, invalid-MBR, and injected-I/O-error devices. Signed-off-by: longjin <longjin@dragonos.org> * fix(ahci): handle disks without flush capability Treat synchronization as a successful no-op only when IDENTIFY reports neither an enabled write cache nor a supported FLUSH CACHE command. This prevents completed writes from being reported as unsupported while preserving real command failures. Track the advertised reliable-flush capability separately from the command selected for synchronization. If write cache is enabled but FLUSH capability bits are absent, follow Linux libata and attempt the base FLUSH CACHE command without advertising a reliable power-loss barrier. Signed-off-by: longjin <longjin@dragonos.org> * fix(ahci): harden detach and link recovery Make PCI removal a non-fallible terminal notification and detach AHCI block devices even while stale userspace or mount references remain. Gate new I/O, stop hardware when accessible, disable bus mastering, and keep delayed drops hardware-silent. Retain DMA allocations when engine shutdown cannot be proven, then reclaim the BDF-keyed quarantine only after a later probe completes an HBA reset with bus mastering disabled. Add irreversible best-effort block-device unpublication for physically detached hardware. Validate the complete 48-bit IDENTIFY capacity, avoid yielding on the first polling iteration, and train candidate links concurrently in one bounded controller window. Stop provisional FIS receivers without invalidating successful link classification. Validated with make kernel, x86_64 workspace tests, QEMU empty-controller boot, and QEMU AHCI disk discovery/read/sync smoke tests. Signed-off-by: longjin <longjin@dragonos.org> * style(ahci): apply rustfmt to stop polling Match the repository rustfmt output for the non-short-circuit provisional port stop expression. FMT_CHECK=1 make fmt now passes, including the kernel clippy check. Signed-off-by: longjin <longjin@dragonos.org> * fix(ahci): bound controller teardown latency Stop all implemented ports in two controller-wide phases: clear ST and wait up to 500 ms for every CR bit, then clear FRE and give every FR bit a separate 500 ms window. Each scan visits every port, so teardown latency no longer scales with port count. Treat an un-stoppable port during multi-port probe as a controller-fatal rollback. Quiesce published I/O, stop or reset the HBA, enter the detached terminal state, retire or quarantine DMA, and unpublish earlier disks before releasing the BDF probe reservation. Reuse the final Bus Master disable, detached publication, and DMA retirement sequence between normal remove and probe rollback so delayed mount references remain hardware-silent. Validated with make kernel, FMT_CHECK=1 make fmt, git diff --check, QEMU AHCI boot/device discovery/sync, and independent architecture, safety, and semantic reviews. Signed-off-by: longjin <longjin@dragonos.org> * fix(ahci): isolate port failures and bound command batches Keep controller-wide Bus Master enabled when a single port cannot stop, quarantine only that port DMA buffer, and reject queued I/O after the port is marked failed. Probe IDENTIFY and teardown FLUSH commands in fair controller-wide batches so one stalled port cannot multiply latency or starve healthy ports. Use the complete Linux AHCI error mask and ordered PxCI/PxIS sampling to avoid false command success. Add compile-time command status checks and preserve bounded concurrent cleanup for all failed ports. Signed-off-by: longjin <longjin@dragonos.org> * fix(ahci): harden firmware handoff cleanup Keep the entry PCI Command value intact until the controller is safe for OS ownership. Follow the AHCI BIOS handoff grace periods, force a bounded takeover without rolling back OOS, and disable bus mastering before resetting firmware DMA state. Restore the original non-DMA PCI decode state on detach. Restrict the on-demand DMA allocator self-test to architectures with implemented page-frame allocation so the LoongArch64 release build does not instantiate its placeholder MMArch. Signed-off-by: longjin <longjin@dragonos.org> * fix(build): restore musl source download The configured DragonOS mirror now returns HTTP 404 for the pinned musl 1.2.4 archive, which prevents x86_64 user-space builds from preparing their environment even though the kernel build succeeds. Use the official musl HTTPS release URL while preserving the pinned version, archive root, and build configuration. The downloaded archive was verified as gzip with the expected musl-1.2.4 root and SHA-256 7a35eae33d5372a7c0da1188de798726f68825513b7ae3ebe97aaaa52114f039. Signed-off-by: longjin <longjin@dragonos.org> * fix(ahci): address lifecycle and DMA review Release the controller registry read guard before taking the per-controller lifecycle lock so shutdown cannot deadlock against concurrent hot removal. Keep scanning a bounded DMA pool after discarding incompatible high-address entries, and strengthen the on-demand allocator self-test with a compatible entry below an incompatible LIFO entry. Skip redundant zeroing only for AHCI host-to-device payloads, which are fully initialized before submission. Device-written, bidirectional, identify, and command buffers remain zeroed. Signed-off-by: longjin <longjin@dragonos.org> * fix(ahci): preallocate DMA quarantine ownership Reserve both the per-controller and global quarantine slots while the HBA is healthy and bus mastering is disabled. Cache the device key so fatal teardown transfers up to 32 port buffers plus the command arena without allocating. Preserve quarantine capacity across successful command-engine stops, release DMA objects outside quarantine locks, and retain ownership rather than panic if a safety invariant is ever violated. Signed-off-by: longjin <longjin@dragonos.org> * fix(build): use reliable musl source mirror Fetch the canonical musl 1.2.4 release archive from the Buildroot source mirror. The archive matches the upstream SHA-256 and layout while avoiding the CI hang observed against the upstream release host. Signed-off-by: longjin <longjin@dragonos.org> * fix(build): fetch musl from GitHub mirror Use the v1.2.4 tag from the GitHub mirror whose commit matches the official musl tag. GitHub Actions can access this archive and its musl-1.2.4 root layout, unlike the Buildroot endpoint that returned non-gzip content to hosted runners. Signed-off-by: longjin <longjin@dragonos.org> * fix(build): pin musl mirror revision Pin the GitHub archive to the full commit referenced by the official musl v1.2.4 tag and update the extracted root directory. This prevents a mutable mirror tag from changing the source selected by clean CI builds. Signed-off-by: longjin <longjin@dragonos.org> * fix(driver-core): serialize device binding lifecycle Serialize probe, unbind, and device removal with a per-device sleeping lock so teardown cannot observe or invalidate a partially committed binding. Revalidate lifecycle state at binding commit and cover preset-driver attachment with the same synchronization and rollback rules. Signed-off-by: longjin <longjin@dragonos.org> * fix(mm): bound dma32 buddy allocation Split buddy free lists into DMA32 and Normal zones and keep non-empty metadata chains so exact 32-bit DMA allocation checks a fixed number of orders while interrupts are disabled. Reuse empty metadata pages, preserve low memory for constrained devices, and extend the on-demand allocator self-test and dunitest contract. Signed-off-by: longjin <longjin@dragonos.org> * fix(driver-core): drain bindings before shutdown Block new probe and preset-driver binding operations once shutdown starts, and wait for admitted bindings to complete before walking the device list. Serialize each shutdown callback with the existing per-device lifecycle lock and use exact device identity for the committed-binding check. Signed-off-by: longjin <longjin@dragonos.org> * fix(ahci): yield during controller polling Centralize the AHCI polling pause policy and use it for firmware handoff, power stabilization, and HBA reset waits so probe and teardown do not monopolize a CPU. Keep the protocol-sensitive 1 ms COMRESET assertion as a busy wait. Correct cold-presence handling while touching the power-settle path: CPD is a per-port PxCMD capability, CPS reports whether a device is attached, and only real SUD/POD transitions require the stabilization delay. Treat a firmware handoff without BB as the normal takeover path instead of a warning. Add compile-time coverage for the SSS/SUD and CPD/CPS/POD state combinations. Tests: make fmt FMT_CHECK=--check Tests: make kernel Tests: make -C kernel check ARCH=riscv64 Tests: make -C kernel check ARCH=loongarch64 Tests: make qemu-nographic (q35 empty AHCI controller, booted to userspace) Signed-off-by: longjin <longjin@dragonos.org> * fix(driver-core): amortize lifecycle lock cleanup Avoid scanning the entire lifecycle lock table on every new device once the table contains 64 live entries. Track an insertion budget and run dead-entry cleanup no more frequently than the current table size, keeping cleanup cost amortized under bulk registration. Preserve live weak entries so every lifecycle operation for the same Device allocation continues to rendezvous on one lock, including across unregister and later references. Signed-off-by: longjin <longjin@dragonos.org> * fix(mm): separate DMA cache address domains Keep DMA32-constrained and wider requests in separate bounded free lists for each DMA size class. Select cached buffers with an exact full-range mask check so a constrained allocation neither consumes nor releases incompatible entries from another device domain. Preserve the logical pool key in DmaBuffer, make pool return ownership explicit, and reserve optional list metadata before taking IRQ-safe locks. Extend the allocator self-test and dunit contract for domain isolation, narrow and 40-bit masks, range boundaries, overflow, and low-memory reuse. Signed-off-by: longjin <longjin@dragonos.org> * fix(ahci): recover ports after command errors Treat an isolated ATA task-file error as a command failure instead of permanently disabling the whole port. Stop command-list processing, validate a coherent PxIS/PxSERR/PxTFD/PxCI/PxSACT/PxSSTS snapshot, clear only observed status, and reopen the port only when the link and engine remain safe. Keep fatal, interface, timeout, hotplug, and ambiguous states fail-closed. Preserve DMA payload ownership until recovery completes, quarantine it when CR cannot clear, and roll back partial engine starts. Reuse cooperative polling in the HBA stop waits so a stuck CR or FR bit cannot monopolize a CPU. Add build-time coverage for recoverable UNC, fatal and overflow status, reset-worthy and recovered SError, ICRC, DRDY, active slots, post-recovery state, and link presence. Tests: make fmt FMT_CHECK=--check Tests: make kernel Tests: make -C kernel check ARCH=riscv64 Tests: make -C kernel check ARCH=loongarch64 Tests: make qemu-nographic (q35 empty AHCI controller, booted to userspace) Signed-off-by: longjin <longjin@dragonos.org> * fix(ahci): harden pre-command timeout recovery Recover a port once with COMRESET when BSY or DRQ remains set before command submission, then reinitialize it and revalidate the device identity with IDENTIFY. Keep the timed-out request failed and isolate the port whenever recovery cannot prove a safe reusable state. Derive command and FIS pointers from the controller-owned command arena instead of trusting mutable MMIO addresses. Remove the teardown allocation by draining the existing weak-device registry in place. Allow DMA32 allocations under buddy pressure to take a compatible low buffer from the unrestricted cache and migrate it one way into the constrained pool. Extend the allocator self-test to cover migration while retaining incompatible high entries. Signed-off-by: longjin <longjin@dragonos.org> * fix(ahci): reject overflowed transfers Treat PxIS.OFS as a command error so a completed slot cannot expose truncated DMA data or report an overflowing write as successful. Keep INFS non-fatal as required by AHCI and pin both cases with compile-time checks. Move the existing gendisk map out of detached block metadata and iterate it directly. This removes the remaining temporary Vec allocation from irreversible AHCI removal while keeping devfs and manager callbacks outside the metadata lock. Signed-off-by: longjin <longjin@dragonos.org> * revert(build): keep musl source configuration unchanged Restore the musl 1.2.4 DADK configuration to the PR base version. The mirror changes are unrelated to the AHCI driver work and should not be included in this pull request. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
fc4146b2d5 |
test(procfs): cover TID reuse refreshing task namespace directory (#2166)
Add a dunitest that verifies /proc/<pid>/task/<tid>/ns/<name> entries follow TID reuse instead of resolving through a stale cached directory. The test spawns a thread, opens and readlinks its IPC namespace file, and confirms the per-TID task directory reports ENOENT once the thread exits. It then reuses the released TID across up to 128 replacement threads, asserting the task directory and its UTS namespace links resolve to the new thread, matching Linux 6.6 semantics. On Linux, TID reuse is not guaranteed within a small fixed attempt budget, so the final assertion is gated to DragonOS and the test skips on other kernels when reuse is not observed. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
4ce6e061d5 |
fix(fs): stabilize epoll and namespace lifecycles (#2165)
* fix(fs): stabilize epoll and namespace lifecycles Eliminate the epoll wait lock inversion by removing the unreachable shutdown state and keeping waiter registration entirely within the ready-state synchronization domain. Refresh proc task entries by PID object identity and thread-group ownership so recycled TIDs cannot resolve stale cached directories. Resolve proc namespace magic links to namespace-backed files and preserve their mount projection through anonymous, non-cached dentries, allowing bind mounts to outlive the source task without leaking wrapper-cache entries. Add concurrent epoll ctl/wait coverage and namespace bind-lifetime regression coverage, including checks that ordinary proc fd magic-link projection remains unchanged. Validation: - make fmt - make kernel - DragonOS proc PID/TID reuse, UTS namespace, epoll, and mount suites - CubeSandbox container create/exec/destroy, 5/5 on the final kernel Signed-off-by: longjin <longjin@dragonos.org> * fix(procfs): preserve namespace fd identities Carry a stable namespace dentry name with mount-projected magic-link targets so open namespace descriptors render type:[inode] instead of falling back to anon_inode. Keep bind-mounted namespace descriptors on the ordinary mount path and expose anonymous namespace roots in mountinfo without a leading slash, matching Linux d_path and nsfs semantics. Extend the namespace bind regression test to cover the original fd identity, the bind-mounted fd path, and the mountinfo root. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
4a99bd415a |
fix(net): restore deadline-driven TCP progress (#2162)
Publish smoltcp future poll deadlines through an atomic per-interface state and notify namespace pollers whenever a sleeping worker must recompute its timeout. Claim due deadlines before handing work to NAPI, restore claims after failed handoffs, and bound direct polling for interfaces without NAPI. Make NAPI schedule and completion results explicit across disable and detach races. Serialize RTNETLINK link mutations so interface state transitions cannot lose deadline rearming or publish inconsistent operational state. Add concurrent state-machine coverage for publish, claim, restore, schedule, complete, and disable transitions. Add a TCP receive-window regression test that verifies receiver progress makes a backpressured sender writable without relying on a fixed buffer threshold. Validated with make fmt, make kernel, net-poll-state and napi-state host tests, plus DragonOS guest TCP window, close, epoll timeout, and RTNETLINK link regression tests. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
a43e491a6a |
fix(ext4): eliminate delayed allocation retry storms (#2161)
* fix(ext4): eliminate delayed allocation retry storms Replace fixed yield and sleep retries with a filesystem-scoped metadata mutation progress bridge. Publish generation changes when the final direct owner or exclusive owner releases the gate, wake all mount waiters on progress and fail-stop, and preserve linear reclaim and delayed-allocation ownership while waiting. Serialize delayed transaction submissions per mount so per-inode workers contend in the same ownership domain as the lower transaction gate. Treat a busy raw transaction core behind an acquired gate as an ownership invariant failure instead of retryable contention. Coalesce physically contiguous journal and checkpoint blocks without changing commit, flush, checkpoint, or clean-tail durability boundaries. Reserve bounded scratch space before publishing the active journal tail and validate immutable journal mappings at core construction time. Add lower-level gate, wraparound, poison, transaction collision, bulk I/O failure, and multi-inode delayed writeback recovery coverage. Validated with: - make fmt - make kernel - cargo test --lib in another_ext4 (161 passed) - recovery_fault_injection crash-recovery matrix - ext4_inode_identity_test in DragonOS QEMU (33 passed) Signed-off-by: longjin <longjin@dragonos.org> * docs(ext4): clarify direct gate retry semantics Document that compatible direct-owner CAS contention must remain a lock-free retry rather than being converted into EAGAIN. Explain the generation invariant that prevents bounded retry exhaustion from having a valid wakeup event. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
8bbc724a95 |
feat(ext4): implement recovery-safe delayed allocation (#2160)
* feat(ext4): implement recovery-safe delayed allocation Introduce a reservation-backed delayed-allocation pipeline that keeps foreground admission, PageCache ownership, ext4 mapping, journal publication, and durable EOF updates in one explicit protocol. - reserve data and extent metadata capacity before publishing dirty pages, with mount-scoped linear leases and fail-stop accounting invariants - serialize per-inode append writeback through opaque capabilities, FIFO claims, stable dirty certificates, and bounded journal credit/extent-node pools - publish initialized data, extents, inode size, and timestamps with crash-safe journal ordering and orphan recovery coverage - coordinate truncate, fsync, mmap, reclaim, eviction, and unmount with admission closure, lifecycle ownership, queue draining, and errseq reporting - strengthen PageCache writeback generations, cancellation, deferred retry, MM fault handoff, and post-commit population semantics - add host power-loss fault injection plus dunitest coverage for queue ordering, inode identity, writeback accounting, sync ranges, and memory locking Signed-off-by: longjin <longjin@dragonos.org> * refactor(mm): split page cache by responsibility Separate the oversized page cache implementation into focused mapping, read-DMA, runtime self-test, and writeback modules while retaining the existing parent facade and public paths. - keep PageCacheManager's Weak<PageCache> ownership model and external API unchanged - isolate VMA invalidation and truncate coordination from cache membership operations - colocate DMA reservation and writeback state machines with their lifecycle helpers - constrain cross-module protocol access to the minimum page-cache-local visibility - preserve all locks, atomic orderings, wait predicates, error paths, and drop semantics Validated with make fmt, make kernel, symbol/declaration equivalence checks, and targeted 2-vCPU QEMU dunitest coverage for page-cache accounting, mmap truncate, sync_file_range, errseq reporting, ext4 I/O, and FUSE. * fix(ext4): batch delayed allocation writeback Aggregate contiguous per-inode delayed-allocation entries at the writeback boundary so a bounded batch shares data flush and journal commit costs without weakening foreground space guarantees. - carry one dirty-incarnation certificate and reservation per page through PageCache selection, ext4 FIFO claim, rollback, completion, and terminal failure paths - let the lower mapper consume fragmented physical allocations in one transaction with transaction-aware extent staging and conservative pre-claim credit bounds - query and clear a partial durable EOF tail before staging a promoted extent root, preserving the single successful data flush - make owner-free Claimed admission waits passive and interruptible while keeping published writeback and journal ownership non-cancellable - extend recovery fault injection for real batch submission, sparse forwarding, extent growth and split/merge, partial EOF root promotion, and I/O failure boundaries Signed-off-by: longjin <longjin@dragonos.org> * fix(fs): harden delayed writeback completion Preserve frozen range ownership across ordinary reclaim and writeback races by excluding tagged pages, serializing Legacy claims with invalidation, and assigning every Writeback transition a unique incarnation. Replace yield-based tagged retry loops with exact incarnation completion continuations. Dispatch retries from success, failure, detach, and deferred completion paths without blocking shared workers or allocating in infallible completion paths. Propagate mapping errseq failures through O_SYNC and O_DSYNC writes, restore delayed-allocation admission after a failed sibling mount, and make FIFO claim admission constant-time. Add PageCache incarnation/invalidation regression coverage and synchronous-write errseq dunitests. Signed-off-by: longjin <longjin@dragonos.org> * fix(ext4): bound mount and direct read serialization Replace the global mount registry critical section with a short lookup of a per-device mount domain. Keep journal recovery and delayed-allocation draining serialized only against mounts of the same block device. Restore delayed-allocation admission through an RAII rollback owner on every failed sibling-mount path, including failures while draining existing owners. Preserve fail-stop fencing while allowing healthy mounts with pending queues to resume. Make O_DIRECT reads persist only the FIFO prefix needed to reach delayed pages overlapping the requested range, then write back eager dirty pages in that range. This matches Linux range-based direct-read coherence without draining an unrelated append tail. Validated with make fmt, make kernel, and the 31-case ext4_inode_identity guest suite. Signed-off-by: longjin <longjin@dragonos.org> * fix(page-cache): bound writeback freeze exclusion Release the mapping invalidation writer between bounded dirty-tag scan chunks so large sync ranges do not stall file faults and other mapping operations for the complete scan. Serialize only competing freeze scanners across chunk boundaries to preserve epoch ownership. Resample the writeback incarnation frontier under the final exclusion window so ordinary claims which run between chunks remain covered by the frozen operation. Add a deterministic runtime self-test which queues an invalidation reader at the initial freeze boundary and verifies that it acquires before the unscanned tail is tagged. Validated with make fmt, make kernel, page_cache_accounting, sync_file_range, ext4_inode_identity, and repeated proc_self_exec_cmdline guest tests. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
ae28b35276 |
fix(process): serialize non-leader exec handoff (#2156)
Model non-leader exec as an owned group-exec transaction that serializes sibling teardown, old-leader exit, fatal cancellation, identity migration, and observer visibility. Atomically preserve PID/TGID/PGID/SID membership, raw-PID lookup, cgroup placement, parent-child ownership, ptrace relations, pidfd identity, session state, and accumulated resource usage across the leader handoff. Align wait, SIGCHLD, ptrace exit notification, fatal thread-group signals, and process-group delivery with Linux 6.6 semantics. Preserve exited-thread CPU accounting and publish child-exit state before waking signal and wait observers. Serialize controlling-TTY ownership and PTY peer lifetime transitions to prevent stale session updates, duplicate group signals, premature ctty removal, and slave-open races. Add deterministic dunitest coverage for non-leader exec identity, pidfd visibility, fatal-signal races, wait ownership, resource accounting, process groups, ptrace siginfo, and PTY lifetime behavior. Fixes #2153 Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
e374b45138 |
fix(kernel): stabilize apt update under sustained I/O (#2157)
* fix(kernel): stabilize apt update under sustained I/O Rework NAPI scheduling around an exact-once SCHED/MISSED state machine with bounded, fair polling. Move virtio-net to deeper raw queues with preallocated DMA buffers, asynchronous TX completion, and race-closing EVENT_IDX callback handling. Track actual cross-CPU task ownership independently from runqueue placement and serialize stop wakeups, affinity changes, and migration tails so a task cannot execute or enqueue twice during network wakeups. Batch ext4 sequential range allocation and orphan extent reclamation, preserve journal credit and checksum invariants, and avoid read-before-write for complete blocks. This prevents apt package-store writes and interrupted-download cleanup from synchronously amplifying metadata I/O. Treat disappearing proc fd and fdinfo tables as normal exit races, refresh the pinned virtio-drivers revision, and add host-testable NAPI transition coverage. Validated with cargo test -p napi-state, cargo test -p another_ext4, and make kernel. Signed-off-by: longjin <longjin@dragonos.org> * fix(kernel): refresh dynamic proc and block state Refresh whole-disk capacity from the backing block device so loop devices expose their configured size after LOOP_SET_FD. Keep the static start LBA on I/O hot paths, safely fall back after device teardown, and report only complete loop sectors. Revalidate cached proc fd and fdinfo entries against the live descriptor table. Return ENOENT across zombie and reaped-task paths, including reads from an already-open fdinfo file, matching Linux 6.6 semantics. Add a dunitest covering cached fd entries across process exit. Signed-off-by: longjin <longjin@dragonos.org> * fix(net): defer virtio response TX reservation Consume completed RX buffers independently of TX queue availability so NAPI can continue making receive progress under transmit pressure. Use a lazy response token for receive-side replies and reserve DMA capacity only when smoltcp actually emits a frame. Keep explicitly reserved tokens for standalone transmit calls and split RX/TX token types to preserve their ownership invariants. Signed-off-by: longjin <longjin@dragonos.org> * fix(net): report standard MTU without blocking boot Keep the smoltcp Ethernet frame limit separate from the user-visible IP MTU so rtnetlink reports 1500 bytes instead of 1514. Run the existing DHCP acquisition window in a kernel worker, allowing SystemState::Running and userspace startup to proceed when no DHCP server is available. Add a strict rtnetlink MTU regression and teach dunitest to parse singular GoogleTest summaries so the one-case suite is enforced by CI. Signed-off-by: longjin <longjin@dragonos.org> * fix(fat): serialize concurrent cluster allocation Signed-off-by: longjin <longjin@dragonos.org> * fix(ext4): bound transactional range probes Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
94d4a8d45d |
fix(kernel): eliminate build warnings (#2155)
Restrict FUSE DAX inspection helpers to test builds and remove stale accessors that no longer participate in production paths. Keep mixed-map PFN classification and initram root attachment semantics explicit without carrying unused state in default builds. Apply the x86_64 noexecstack policy to both kernel link passes so the final ELF advertises a non-executable GNU stack and no longer relies on deprecated linker inference. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
1f4e6b60ab |
fix(pipe): correct waitqueue wakeup semantics (#2148)
* fix(pipe): correct waitqueue wakeup semantics Track blocked writer intents while holding the pipe state lock and choose single or broadcast wakeups according to whether heterogeneous write predicates may be waiting. Reuse the lock guard returned by the wait path so predicate publication, sleep, and revalidation remain ordered. Move waitqueue, epoll, async I/O, and SIGPIPE notifications outside pipe spinlocks. Preserve partial-write results and observer notifications when readers close, and align zero-length, nonblocking EPIPE, resize, splice, and tee behavior with Linux semantics. Prevent splice-held data from being consumed twice and keep tee source data intact while preserving partial progress. Add deterministic dunitest coverage for endpoint side effects, writer eligibility, partial-write notifications, splice and tee wakeups, reader baton passing, and resize threshold changes. Signed-off-by: longjin <longjin@dragonos.org> * fix(pipe): select eligible writer waiters Replace unconditional multi-writer broadcasts with predicate-tagged waits. Track the free-space requirement of each blocked writer, choose one eligible class in round-robin order, and wake only that class to avoid thundering-herd retries. Preserve progress with bounded fallback across the register-before-enqueue window. Pass the writer baton only after the selected write or splice operation completes or aborts, and pass the reader baton when an interrupted reader leaves consumable data behind. Keep tagged waitqueue lookup and cleanup bounded, reserve the ordinary waiter tag, and move wake-all destruction outside the IRQ-disabled critical section. Add homogeneous and heterogeneous writer, splice, tee, signal, and resize regression coverage. Tests: make fmt Tests: make kernel Tests: pipe_waitqueue_wakeup_test (11/11) Tests: pipe_release_test (8/8) Tests: splice_concurrent_io_test (7/7) Tests: epoll_timeout_budget_test (1/1) Tests: TCPResetDuringClose (12/12, twice) Signed-off-by: longjin <longjin@dragonos.org> * fix(pipe): serialize splice writer transactions Add a per-pipe writer transaction that coordinates writes, output-side splice operations, endpoint close, and pipe resizing. Blocking writers publish their tagged wait predicate before releasing the transaction and pass an eligible writer baton only when another published waiter remains. Keep file-to-pipe splice ownership across the input read and commit so competing writers cannot steal previously observed capacity. Validate readers before consuming stream input, including nonblocking EPIPE handling, and retain destination-only transaction locking for pipe-to-pipe splice and tee to avoid ABBA. Add Dunitest regressions for no-reader stream preservation and competing writer serialization. Bound regression reads with poll deadlines so incorrect behavior fails deterministically instead of timing out. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
229557c64e |
fix(timekeeping): restore monotonic clock and clocksource semantics (#2145)
* fix(timekeeping): restore monotonic clock and clocksource semantics DragonOS used the realtime epoch as the basis for monotonic clocks and spread clocksource cycle state across multiple owners. The resulting updates could lose elapsed time, recurse through the timekeeper lock, and make timeout consumers depend on wall-clock adjustments. KVM clock CPU bring-up and interrupt-context locking also lacked transactional failure handling. Rework the timekeeping core around independently maintained monotonic and raw read bases, with realtime and boottime represented as offsets. Keep clocksource selection, watchdog state, switching, and rollback under a single control transaction, and preserve elapsed time and fractional state when a source changes. Make KVM clock setup per-CPU and transactional, including AP failure rollback. Add writer-preferred RwLock progress and explicit interrupt context tracking so timekeeper writers cannot deadlock behind continuous readers or acquire blocking paths from hardirq/softirq context. Align POSIX clock reads, nanosleep restart handling, signal waits, and futex timeouts with their Linux clock domains. Add kernel selftests, dunitest coverage, a guest calibration workload, and a fail-closed host calibration harness for KVM and TCG evidence. Validation: - x86_64 kernel build and link - RISC-V Rust build and kernel ELF link - 31 host calibration unit tests - guest calibration workload static build - QEMU runner and Python syntax checks - KVM 2-vCPU timekeeping/restart suite: 19/19 relevant tests passed - fixed-CPU and migrating 10,000,000-read monotonicity tests passed Signed-off-by: longjin <longjin@dragonos.org> * fix(timekeeping): address CI and review regressions Serialize watchdog cleanup with clocksource registration and fully roll back partially published watchdog state. Keep hardirq nesting counters cache-line isolated and avoid the CAS loop on interrupt entry and exit. Match Linux's settimeofday boundary after suspend, expose clocksource selftests through debugfs, and bound normal guest semantic loops while retaining the opt-in ten-million-read stress gates. Make QEMU argv evidence fail closed, release partially initialized serial transport resources, and resolve the formatting regressions reported by CI. Validated with make fmt, make kernel, host calibration tests, the calibration host build, and DragonOS guest timekeeping selftest and semantics suites. Signed-off-by: longjin <longjin@dragonos.org> * fix(timekeeping): preserve selftest execution state Restore preemption when an already-registered rwlock writer acquisition fails, and cover the failure path in the debugfs selftest. Consolidate all selftest-only registered writer attempts behind the balanced helper. Also preserve the underlying serial socket error in calibration diagnostics and verify both the reported detail and resource cleanup. Validated with format and Clippy checks, the kernel build, calibration unit and host tests, and DragonOS guest timekeeping selftests. Signed-off-by: longjin <longjin@dragonos.org> * fix(net): snapshot bound sockets before notification Network polling walked the bound-socket vector by index while dropping the lock around every notification. Concurrent socket teardown could remove an earlier entry, shift the vector, and make the next index skip a poll waiter entirely. Take one coherent Arc snapshot and reuse the shared notification path for regular polling, NAPI polling, and listener teardown. Notifications still run outside the bounds lock, preserving the required lock order, while a single read-side acquisition avoids writer-fair reacquisition stalls under close-heavy workloads. This prevents tcp_close_semantics poll timeouts during concurrent IPv4 and dual-stack reset/close stress. Signed-off-by: longjin <longjin@dragonos.org> * fix(process): serialize kernel stack allocation safely Kernel stack allocation and reclamation used try_lock_irqsave().unwrap() on their shared mapper lock. Concurrent fork and exit activity therefore converted ordinary lock contention into a kernel panic, as observed when tcp_socket_test created processes on both CPUs. Acquire KSTACK_LOCK with the blocking irqsave spin-lock operation in both paths. This preserves the existing mapper serialization and interrupt exclusion while allowing the contending CPU to wait for the current stack operation to finish. The gVisor tcp_socket_test now completes all 184 tests without triggering the allocation race. Signed-off-by: longjin <longjin@dragonos.org> * fix(kernel): avoid poll allocation and TTY lock recursion Make the network interface's bound-socket table copy-on-write. Poll and notification paths now clone only the outer Arc while interrupts are disabled, while the less frequent bind and unbind paths perform any required Vec clone. This preserves a coherent notification snapshot without O(n) IRQ-off allocation or the index-shift race fixed earlier. Use one by-value termios snapshot for each N_TTY receive batch and pass it through the nested input helpers. The previous receive path recursively acquired the same read lock; once a termios writer queued, writer-fair admission blocked the recursive reader and deadlocked both CPUs. A value snapshot preserves consistent per-batch input semantics and removes the recursive locking dependency. Validated with make kernel, all 27 CubeSandbox PTY exec-chain tests, and all 6 TCP close semantics tests. Signed-off-by: longjin <longjin@dragonos.org> * style(kernel): format N_TTY snapshot changes Apply the repository rustfmt output required by the architecture format-check jobs. No behavior changes. Signed-off-by: longjin <longjin@dragonos.org> * fix(x86_64): roll back failed HPET enablement Treat HPET enablement as a hardware transaction. If any validation, counter check, timer lookup, or IRQ registration step fails, restore the firmware general configuration instead of relying on the enabled flag, which is intentionally published only after IRQ setup succeeds. Snapshot and restore each timer comparator together with its configuration. Restore timer state while the counter is disabled, then write the complete firmware general configuration last so a firmware-enabled counter resumes only after all timer registers are coherent. Normal HPET disable now reuses the same restoration path. Validated with the repository format and Clippy checks, make kernel, and a DragonOS x86_64 fallback boot with HPET unavailable. Signed-off-by: longjin <longjin@dragonos.org> * fix(tty,time): eliminate PTY input hangs Use a persistent waiter notification for nanosleep timers, preserve deadline semantics across signal and restart races, and avoid recursive N_TTY termios, flow, and line-discipline wakeup locking during input processing. This fixes the ByteStream PTY deadlocks observed in CI while keeping absolute sleeps from returning before their POSIX clock deadline. Signed-off-by: longjin <longjin@dragonos.org> * fix(tty): satisfy clippy auto-deref lint Signed-off-by: longjin <longjin@dragonos.org> * fix(dunitest): synchronize reparent wait test Signed-off-by: longjin <longjin@dragonos.org> * fix(time): return EOPNOTSUPP for thread CPU nanosleep Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
45931ee3b3 |
chore(rootfs): remove deprecated default apps (#2146)
Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
e683b2062c |
fix(namespace): pass mount and pivot_root conformance (#2137)
* fix(namespace): pass mount and pivot_root conformance Align mount namespaces, propagation, pivot_root, proc mount topology, VFS permissions, and tmpfs accounting with Linux 6.6 semantics. Make current-task publication and x86 fast CPU identification safe across context switches and AP startup, and harden page-cache allocation and rollback paths. Add focused dunit and gVisor coverage for mount, pivot_root, dangling symlinks, tmpfs quota, and propagation. Make both runners fail closed on incomplete XML, unexpected skips, timeouts, and stale results while always publishing CI artifacts. Validated with kernel builds, runner unit tests and linting, slab allocator tests, QEMU boot, the full dunit suite, focused namespace tests, and gVisor mount/pivot_root tests. Signed-off-by: longjin <longjin@dragonos.org> * fix(vfs): address review and CI regressions Make atime updates field-specific and synchronized in mutable filesystems, serialize FUSE and ext4 metadata updates, enforce O_NOATIME ownership, and cover directory access semantics. Compute tmpfs statfs data from atomic page accounting without taking a superblock write lock on every page operation. Preserve slab allocator soundness without clearing an entire object page. Restore the origin/master current-task implementation that predates the wait/epoll CI regressions, reject invalid open flag combinations, read complete symlink targets, and decouple existing mount topology traversal from mount-max admission limits. Add dunit coverage for metadata races, atime flags, tmpfs quota reporting, long symlinks, open errors, and lowered mount limits. Signed-off-by: longjin <longjin@dragonos.org> * fix(vfs): skip atime updates for anonymous inodes Use the optional filesystem lookup before checking mount state during access-time updates. Anonymous kernel objects such as sockets now report that they are not backed by a filesystem, matching Linux socket read semantics and avoiding a panic in readv and splice paths.\n\nDocument the expanded try_fs contract so callers can distinguish filesystem-backed inodes from anonymous objects without relying on a panicking fs implementation.\n\nThis fixes the gVisor TCP splice timeout and UDP writev/readv failure observed in the integration workflow. Signed-off-by: longjin <longjin@dragonos.org> * fix(vfs): address follow-up review findings Preserve Linux open error precedence by applying O_NOATIME ownership checks after path, type, and DAC validation while keeping them ahead of direct-I/O and socket-open failures. Add regression coverage for final symlinks and directory O_DIRECT combinations.\n\nReuse one fallibly allocated PATH_MAX buffer across a symlink walk to avoid per-hop allocation and clearing.\n\nEnsure the gVisor runner terminates the full test process group and reaps its leader when try_wait fails, sharing the same cleanup path used for timeouts. Signed-off-by: longjin <longjin@dragonos.org> * fix(vfs): address latest review and integration failures Initialize new inode ownership before publication across tmpfs, ramfs, and ext4, including mknod and rename whiteouts. Preserve setgid directory inheritance while stripping unauthorized executable setgid modes. Harden transactional page-cache rollback against concurrent dirty publication, update regular-file atime on EOF reads, and avoid filesystem lookups for anonymous socket permission checks. Disable required-test manifest enforcement completely when requested and add regression coverage for ownership, SGID, EOF atime, and runner behavior. Signed-off-by: longjin <longjin@dragonos.org> * fix(vfs): preserve bootstrap inode creation Use the initial root credential for kernel-owned filesystem objects created before ProcessManager installs a current task. Keep setgid directory inheritance intact while avoiding an early-boot current_pcb spin during procfs initialization. Signed-off-by: longjin <longjin@dragonos.org> * fix(vfs): preserve fallocate metadata and defer atime writes Apply Linux-compatible write-side metadata effects after successful tmpfs fallocate allocation, including timestamp updates and setid removal, while preserving rollback atomicity. Cache ext4 atime updates in memory, track them through the existing dirty inode queue, and commit them with size and mtime during periodic or explicit metadata writeback instead of synchronously writing from the read path. Add dunitest coverage for fallocate metadata effects, failure stability, setid clearing, and ext4 atime visibility and persistence. Signed-off-by: longjin <longjin@dragonos.org> * fix(vfs): address symlink and ext4 timestamp review Enforce Linux symlink creation semantics in the common syscall path, including empty targets, trailing slashes, parent search/write permission ordering, immutable directories, and an atomic tmpfs permission recheck under the parent inode lock. Keep ext4 inode timestamps authoritative in memory and evaluate relatime without io_lock or disk getattr. Add masked setattr support and generation-based atime/mtime writeback commits so concurrent reads, writes, mmap faults, setters, resize, and writeback cannot lose dirty timestamp updates. Add dunitest coverage for symlink error and permission semantics plus ext4 relatime behavior. Validated with make kernel and the full DragonOS dunitest suite (797 tests, 0 failures). Signed-off-by: longjin <longjin@dragonos.org> * ci(test): align job and guest timeout budgets Raise the syscall workflow timeout to cover its 50-minute guest monitor after the build and disk preparation phases, while preserving time for cleanup and diagnostic uploads. Apply the same outer-timeout invariant to dunitest so its 30-minute monitor can terminate QEMU and publish the serial artifact before the Actions job deadline. Signed-off-by: longjin <longjin@dragonos.org> * fix(ext4): publish created inode without reread Return authoritative attributes from the in-memory inode used by create, mkdir, and mknod transactions, while preserving the existing inode-number APIs. Initialize canonical VFS inodes from those attributes for regular creation, special nodes, and rename whiteouts. This removes the post-link getattr failure window that could report EIO after the directory entry was already committed. Keep lookup-time getattr behavior unchanged and add coverage for complete in-memory FileAttr conversion. Validated with make kernel, all 130 another_ext4 tests, and the full DragonOS dunitest suite (797 tests, 0 failures). Signed-off-by: longjin <longjin@dragonos.org> * fix(namespace): stabilize propagation conformance checks Replace the scheduler-dependent recursive propagation observer with explicit shared/private phase acknowledgements and a midpoint stress snapshot handshake. Preserve the two unsynchronized 512-transition halves, namespace copying, and concurrent topology mutation while reporting the exact failing child status. Allocate a fresh conceptual hidden-parent mount ID when copying an attached namespace so mountinfo never exposes the source namespace's parent identity. Keep ordinary overlay traversal single-pass for the common shallow path and defer cycle detection to pathological depths without imposing a semantic limit. Require the recursive-bind topology and mount-limit rollback suites to remain skip-free alongside the existing namespace conformance binaries. Validated with make kernel, 12 dunit runner tests, the full DragonOS dunit suite, and 100-run focused stress loops on Linux and in the DragonOS guest. Signed-off-by: longjin <longjin@dragonos.org> * fix(namespace): address propagation review findings Signed-off-by: longjin <longjin@dragonos.org> * fix(mm): preserve zero-length mmap error priority Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
b1824fc166 |
docs: translate Chinese comments to English in PR #2110 BPF filter files (#2140)
Translate all newly added Chinese doc comments and inline comments in kernel/src/bpf/classic.rs, kernel/src/net/socket/packet/mod.rs, and kernel/src/process/seccomp.rs to English for consistency with the codebase conventions. |
||
|
|
673dcd23a3 |
perf(ext4): batch nojournal range allocation (#2135)
* perf(ext4): batch nojournal range allocation CubeSandbox tmp writes on nojournal ext4 allocated and published every missing 4 KiB block independently. Each block synchronously rewrote allocation metadata, zeroed data, and updated the inode, keeping virtio-blk at queue depth one and amplifying fixed request latency. Add a bounded DirectRangeStage for depth-zero contiguous appends. Plan allocation metadata in transaction-private images, bulk-zero the complete range, enforce a reliable pre-publication flush, and publish bitmap, group descriptor, superblock, and inode homes in semantic order. Runtime failures restore allocation homes when safe and poison the direct backend when inode state or rollback durability is uncertain. Add fallible DMA/BIO construction, exact block I/O completion handling, bounded contiguous ext4 block transfers, and compile-time-disabled block/ext4 diagnostic counters. Preserve journaled, fragmented, sparse, small-write, unsupported-flush, and resource-pressure behavior through explicit legacy fallbacks. Cover extent validation, unwritten tails, allocation bounds, zero and flush failures, every allocation-home failure, rollback failures, inode uncertainty, and transaction snapshot ownership. The nojournal crash contract remains unchanged: abnormal power loss still requires fsck. Validation: make fmt; cargo test --manifest-path kernel/crates/another_ext4/Cargo.toml --lib; RUST_MIN_STACK=33554432 make kernel; local nojournal ext4 hash and e2fsck; CubeSandbox fresh-volume A1/B/A2 performance and hash checks. Signed-off-by: longjin <longjin@dragonos.org> * fix(ext4): address direct range review findings Make nojournal direct-range publication flush allocation metadata before writing the inode home block. If the durability barrier fails, restore and flush every allocation home; poison the backend when rollback durability cannot be established. Add fault-injection coverage for the new ordering and failure states. Keep coherent DMA memory in the normal write-back direct mapping instead of changing RAM cache attributes without architecture cache maintenance. Reject unsupported non-coherent cache policies explicitly, removing partial multi-page remaps and TLB shootdowns from allocation and interrupt-context release paths. Prune expired ext4 statistics registry entries during mount registration so repeated mount/unmount cycles do not retain dead Weak control blocks. Signed-off-by: longjin <longjin@dragonos.org> * fix(io): address direct range review findings Classify nojournal direct-range candidates under the compatible metadata gate before requesting an exclusive transaction snapshot. Unsupported small, overwrite, sparse, and oversized writes now continue directly through the legacy allocator, while real candidates are re-read and revalidated after exclusive acquisition to avoid stale plans. Restore zero-length virtio-blk synchronous I/O semantics by returning Ok(0) before buffer validation or BIO submission. Keep zero-length read/write BIOs invalid as an internal submission invariant. Add direct-range eligibility coverage for the optimized and legacy request shapes. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
7383e9a850 |
fix(vfs): complete pivot_root topology semantics (#2134)
* fix(vfs): complete pivot_root topology semantics Reject unattached namespace roots while preserving Linux 6.6 errno precedence for identity loops, shared parents, disconnected dentries, and locked mounts. Keep the topology transaction allocation-free after its first edge mutation, add test-only reservation failure injection, and verify lock transfer plus exact mount topology through expanded guest tests. Wake both endpoints when Unix stream or seqpacket shutdown publishes shared ring state, including level-triggered RDHUP/HUP events. This fixes the synchronization primitive used by the original gVisor locked-root tests. Add bounded shutdown wakeup regressions and run them by default through the dunitest whitelist. Fixes: #2105 Signed-off-by: longjin <longjin@dragonos.org> * fix(kernel): address pivot_root review findings Preserve the hidden rootfs attachment semantics for normal boot roots and mount namespace copies while continuing to reject the initial rootfs and initramfs. Restore namespace-root pivot transactions without weakening topology validation or atomic publication. Make Unix stream and seqpacket receive paths consistently treat local SHUT_RD as EOF after draining queued data, and make event queries safe when racing with close. Add focused regression coverage for namespace-root pivots, attachment copying, shutdown EOF, poll, recvmsg, and waiter wakeups. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
891fa324f3 |
fix(vfs): use caller fs root for pivot_root (#2130)
* fix(vfs): use caller fs root for pivot_root Resolve and pin the caller fs root, new_root, and put_old as mount-aware paths so pivot_root follows Linux object identity and reachability semantics after chroot. Serialize task publication with exact root/pwd migration, keep mount and dentry topology under one guard, and pre-reserve all edge and task-tracking capacity before the infallible commit. Preserve stacked mount ordering and Linux errno precedence without visible-path approximations. Add focused dunitests for chrooted pivots, namespace-root failures, cross-process fs reference updates, stacked mounts, symlink and bind aliases, and unrelated upper mounts. Tests: make kernel Tests: test_pivot_root_test (20/20) Tests: mount_object_topology_test (9/9) Tests: mount_move_test (11/11) Tests: mount_propagation_test (24/24) Signed-off-by: longjin <longjin@dragonos.org> * fix(vfs): address pivot_root review races Restore the namespace-root pivot path while preserving DragonOS mount namespace invariants and publish the replacement root only after the topology commit is complete. Serialize fs_struct copying and publication against pivot_root migration with a reader-writer barrier covering fork, unshare, setns, and exec namespace switches. Extend pivot_root coverage to verify the standard namespace-root operation and the old-root attachment. Signed-off-by: longjin <longjin@dragonos.org> * test(vfs): cover shared namespace root pivot Distinguish the caller's shared root mount from the private parent of the new root, matching Linux pivot_root propagation checks. Keep markers on both the replacement root and the relocated old root so the test also verifies the committed topology. Signed-off-by: longjin <longjin@dragonos.org> * fix(process): release fs slot before cleanup Clear the exiting task's filesystem slot under its update lock, then release the lock before dropping the final FsStruct owner. This matches Linux exit_fs lifetime ordering and keeps path-pin and mount lifecycle cleanup outside the pivot_root slot critical section. Signed-off-by: longjin <longjin@dragonos.org> * fix(vfs): avoid pivot_root lock inversion Acquire every dentry mount gate touched by pivot_root before taking the dentry topology snapshot. Sort and deduplicate the fixed gate set, and require an unforgeable commit token for prelocked mount-edge operations so the canonical order is enforced by the API. Revalidate namespace membership, exact mount roots, connectivity, propagation constraints, and path reachability only after lifecycle, namespace, gate, and dentry locks are held. Keep all fallible reservations before the first edge mutation and preserve the topology guard across fs reference repair. This removes the ABBA cycle with unlink, rmdir, and rename, which acquire mount gates before the dentry topology writer. Signed-off-by: longjin <longjin@dragonos.org> * style(vfs): satisfy repository format checks Apply the repository rustfmt layout and remove a needless borrow reported by the deny-by-default clippy configuration. Signed-off-by: longjin <longjin@dragonos.org> * perf(process): narrow fork fs publication barrier Complete signal, address-space, architecture, and metadata copies before entering the fs reference publication barrier. Keep copy_fs and copy_namespaces adjacent, and retain the read guard through namespace-dependent PID setup and final PCB publication. Release the guard immediately after add_pcb so pivot_root still observes every copied fs_struct without making unrelated cgroup accounting and fork counters part of the global critical section. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
c6808a8cd6 |
fix(mm): balance page cache membership accounting (#2131)
* fix(mm): balance page cache membership accounting Track immutable file and shmem membership on each page-cache entry so removal and final cache teardown can update VM counters exactly once without upgrading an owner that is already being destroyed. Keep dirty, writeback, and unevictable accounting tied to the currently mapped entry. Revalidate entry identity across truncate and writeback completion, and require the legacy reclaimer to claim the expected physical page before submitting stale snapshots. Preserve the existing PageEntry layout, use vacant-only insertion, and align tmpfs construction with immutable shmem classification. Add a debugfs accounting selftest and dunitest coverage for membership, inflight teardown, late completion, aggregate VM wiring, and layout stability. Validated with make fmt, make kernel, the page-cache accounting dunitest, FUSE core and extended suites, repeated non-DAX VirtioFS mount/read/unmount beyond guest RAM, and CubeSandbox master/candidate performance checks. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
56acd9bfd5 |
perf(virtiofs): isolate virtio PCI interrupt vectors (#2129)
* perf(virtiofs): isolate virtio PCI interrupt vectors Allocate monotonic x86 PCI MSI/MSI-X vectors for interrupt-driven VirtIO transports instead of routing every device through vector 56. Rebind allocated descriptors to the local APIC edge flow, skip reserved vectors, and keep allocation fail-safe until a complete free_irq lifecycle exists. Defer vector allocation until IRQ setup so polling-only transports remain usable on architectures without PCI MSI support. Centralize PCI and MMIO IRQ registration in the transport layer, remove duplicate sysfs registration, and avoid descriptor lock recursion in the shared-action mismatch path. Keep PCI ISR acknowledgement owned by the hard IRQ path while retaining bridge-side acknowledgement for polling fallback. Add a deterministic parallel-read workload with immutable per-worker files, bounded low-impact start coordination, aligned wall/CPU measurement boundaries, exact EOF and checksum validation, and transcript regression coverage. Validated with make fmt, make kernel, host transcript tests, and a fresh-boot non-DAX VirtioFS mount/read smoke test across VirtIO filesystem, block, network, and console devices. Signed-off-by: longjin <longjin@dragonos.org> * fix(virtio): defer MMIO IRQ registration Return an explicit deferred IRQ token for MMIO transports so the global IRQ action is installed only after the concrete virtio device has completed construction. Keep the existing PCI setup path unchanged. Preserve per-device failure semantics: block, net, and console devices abort registration without panicking; pmem falls back to polling. Clean up the block worker, queues, transport, and allocated device ID when deferred IRQ installation fails. Retain virtio-net dispatch registration at the end of probe so interrupts are routed only after the network interface is ready. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
4816406676 |
fix(namespace): lock cross-user mount copies (#2128)
Downgrade shared mounts to slaves when a mount namespace is copied into a different user namespace, and preserve Linux-style topology and per-mount attribute locks across copies and propagation. Require CAP_SYS_ADMIN in the superblock owner user namespace before ordinary remounts can reconfigure shared filesystem state. Keep bind remounts scoped to per-mount flags. Prepare peer and slave registry capacity before publishing copied mounts so allocation failures cannot expose partial propagation state. Add focused failure-injection and dunitest coverage for ordering, propagation direction, locked attributes, remount permissions, and nested copies. Closes #2103 Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
7d2915fe85 |
feat(namespace): enforce mount namespace limits (#2127)
* feat(namespace): enforce mount namespace limits Add Linux-compatible per-mount-namespace accounting with committed and pending reservations. Reserve complete local, recursive, propagated, moved-copy, and namespace-copy mount trees before publication, commit only after topology updates succeed, and release capacity exactly once during unmount or namespace teardown. Expose /proc/sys/fs/mount-max with the Linux 6.6 default and numeric sysctl offset, range, token, and short-write semantics. Keep propagation admission incremental so an ENOSPC failure stops constructing further peer or slave copies, and make detached-copy failure cleanup allocation-safe and deadlock-free. Add guest dunitests for sysctl compatibility, exact boundaries, recursive bind rollback, propagation and shared move atomicity, namespace copy admission, concurrent creators, and capacity reuse. Fixes #2102 Signed-off-by: longjin <longjin@dragonos.org> * ci: enable disk save mode for x86 tests Set DISK_SAVE_MODE at the workflow level so every integration-test step inherits the disk-saving configuration from job startup. Remove the redundant syscall-test step override while preserving the existing Makefile behavior. Signed-off-by: longjin <longjin@dragonos.org> * fix(namespace): allow copying over-limit mount namespaces Match Linux 6.6 by treating mount namespace copies as existing topology rather than newly admitted mounts. Initialize the copied namespace accounting directly, while keeping mount-max enforcement for subsequent mount creation. Update the dunitest regression to require CLONE_NEWNS to succeed after mount-max is lowered and verify that new mounts still fail with ENOSPC. Signed-off-by: longjin <longjin@dragonos.org> * fix(procfs): protect global mount-max writes Revalidate the caller's global effective UID for every mount-max write, matching Linux's 0644 sysctl permission check and preventing child user namespace capabilities from modifying the global limit. Cover inherited descriptors, reopen behavior, and the Linux-compatible global-root case with dunitest regression tests. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
f5883d55c7 |
perf(virtiofs): eliminate readdir per-entry lookups (#2125)
* perf(virtiofs): eliminate readdir per-entry lookups Preserve filesystem-provided inode, type, and opaque cookie data through FUSE, VFS, mount wrappers, and overlayfs so directory scans no longer fall back to lookup plus getattr for every entry. Serialize per-open directory snapshots with seek state, implement READDIRPLUS_AUTO behavior, bound the positive lookup cache with lazy LRU eviction, and retain overlay inode identity and whiteout semantics. Extend the virtiofs benchmark with deterministic readdir datasets and request-count assertions, and add dunitest coverage for typed records, cookie resume, shared-fd concurrency, AUTO request sequencing, and overlay lower-layer scans. Signed-off-by: longjin <longjin@dragonos.org> * fix(fuse): harden readdir compatibility Preserve opaque FUSE directory cookies and raw name bytes through the VFS getdents path. Keep per-open snapshots stable across zero-cookie records and undersized userspace buffers, detect daemon offset cycles without rejecting valid records, and retry READDIR after READDIRPLUS returns ENOSYS. Guarantee RELEASEDIR after every opened-directory request or parser failure, balance non-UTF-8 READDIRPLUS lookup references with FORGET, and forward byte-oriented lookup through mount wrappers and overlay whiteout checks. Restore bounded positive-cache expiry cleanup without scanning or perturbing live LRU entries. Correct the local test daemon's root-child enumeration and populate READDIRPLUS validity fields so the tests exercise real Linux-compatible cache behavior. Validated with make fmt, make kernel, FuseCore 5/5, and FuseExtended 70/70 in a DragonOS QEMU guest. Signed-off-by: longjin <longjin@dragonos.org> * fix(vfs): resume rebuilt directory snapshots Honor a nonzero saved directory cookie when getdents rebuilds a snapshot after rewind. Use one cookie-to-index path for both lseek against an existing snapshot and deferred positioning after a new snapshot is populated. Keep zero-cookie streams distinct from an explicit rewind, and preserve the selected entry across an undersized getdents buffer. Extend the FUSE typed-directory regression with rewind, saved-cookie seek, EINVAL retry, and resume assertions. Validated with make fmt, make kernel, FuseCore 5/5, and FuseExtended 70/70 in a DragonOS QEMU guest. Signed-off-by: longjin <longjin@dragonos.org> * fix(vfs): preserve directory cursor semantics Treat SEEK_CUR with a zero delta as a serialized position query so zero and repeated opaque cookies cannot rewind a live directory snapshot. Reject cookies outside the signed getdents64 and lseek range before emitting a record or advancing file state. Make native typed directory records an explicit optional capability. FUSE and overlay keep their typed fast path, while legacy filesystems cache names and resolve metadata only as the caller buffer advances; overlay materializes legacy metadata only when a full layer merge requires it. Balance READDIRPLUS lookup references when a complete name is followed by truncated alignment padding without changing Linux short-record behavior. Extend coverage for zero and duplicate cookies, SEEK_CUR queries, signed-cookie bounds, and truncated lookup accounting. Validated with make fmt, make kernel, FuseCore 5/5, FuseExtended 70/70, and DevtmpfsSemantics 7/7 in a DragonOS QEMU guest. Signed-off-by: longjin <longjin@dragonos.org> * fix(virtiofs): report readdir pre-scan failures Ensure readdir_scan always terminates its transcript with a machine-readable result when pre-scan quiescence times out or the statistics baseline is unavailable. Preserve the first failure while closing the dataset directory and report ETIMEDOUT or EIO explicitly. Extend the host transcript regression suite to exercise both failure paths and verify their single-result contract. Signed-off-by: longjin <longjin@dragonos.org> * fix(fuse): synchronize shared readdir test workers Replace volatile start, stop, and readiness flags in the shared-directory readdir regression with C++ atomics. Use release stores and acquire loads so worker startup and shutdown have defined happens-before relationships on optimized and weakly ordered targets. Keep worker result fields non-atomic because they are consumed only after pthread_join, which provides the required completion synchronization. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
fcfc8eb8ce |
fix(vfs): snapshot recursive bind topology (#2123)
Hold the mount lifecycle and dentry topology snapshot across source validation, detached root preparation, and recursive child cloning. This aligns the operation with Linux copy_tree semantics and prevents root and descendants from observing different mount states. Keep filesystem metadata checks outside the topology critical section so FUSE requests cannot block global mount and rename progress. Add regression coverage for unbindable subtree filtering and colliding parent-side inode numbers across independent FUSE instances. Fixes: #2101 Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
72ebe13f64 |
perf(virtiofs): batch non-DAX writeback (#2122)
* perf(virtiofs): batch non-DAX writeback Buffer writes in the generic page cache only after FUSE_WRITEBACK_CACHE is negotiated, then claim and submit bounded contiguous batches according to the negotiated write and page limits. Preserve Linux-compatible fsync, close, truncate, mmap, invalidation, stable EOF, redirty, short-write, and errseq behavior. Separate terminal writeback completion from generic page-cache workers so host invalidation cannot strand published Writeback pages behind its own waiters. Harden kernel-thread creation and wakeup ordering required by the new worker pools. Add exact FUSE/page-cache counters, benchmark phase reporting, focused FUSE regressions, and root-only kthread and completion-domain selftests. Validated with make kernel -j2, kernel formatting and diff checks, the completion-domain selftest, targeted close/flush coverage, and FuseExtended 69/69 in a DragonOS guest. Signed-off-by: longjin <longjin@dragonos.org> * refactor(fuse): group negotiated io limits Pass negotiated read, write, page, capability, and effective payload limits through a dedicated stats value object. This keeps the INIT statistics update cohesive and satisfies the project-wide Clippy argument-count lint enforced by make fmt without changing the negotiated values or publication ordering. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
6c6d313a87 |
fix(namespace): implement propagated unmount transactions (#2121)
* fix(namespace): implement propagated unmount transactions Resolve propagated unmount targets by exact parent and mountpoint identity, process the complete local source subtree, and compute Linux-compatible mark, remove, restore, and lazy-retain decisions before mutation. Commit mount-edge and propagation-graph changes under the topology lock with prepared capacity and exactly-once lifecycle cleanup. Preserve root stack ordering, locked root restoration, and detached-connected locked descendants. Add object-level topology coverage and DragonOS dunitest regressions for private children, complete subtrees, blockers, root covers, selected toppers, locked descendants, and propagation chains. Fixes: #2100 Signed-off-by: longjin <longjin@dragonos.org> * fix(namespace): unmount visible propagated shadow Map Linux's mount-hash head lookup to DragonOS's visible stack topper. DragonOS stores direct mounts oldest-to-newest, so selecting the first vector entry could detach a hidden lower mount instead of the propagated mount that is currently visible. Use lookup_top consistently during target preparation and final validation, remove the misleading lookup_first helper, and add a regression test for a direct [lower, top] shadow stack. Signed-off-by: longjin <longjin@dragonos.org> * test(namespace): cover tucked shadow restoration Document the Linux 6.6 distinction between a normal nested overmount and the flat-source race that tucks an older propagated copy below the new copy root. Verify that propagated lazy unmount removes the new copy while restoring the tucked lower copy with exact edge, backlink, and lifecycle invariants. Also express the propagation closure scans with iterators so the repository-wide make fmt clippy gate passes without changing behavior. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
d5440446f3 |
perf(virtiofs): reuse create handles for atomic open (#2120)
FUSE_CREATE already returns an opened file handle, but the VFS create path discarded it with FUSE_RELEASE and constructed the file through a second FUSE_OPEN. This added two protocol requests for every created file and amplified metadata-heavy container workloads. Add an optional VFS create-and-open operation backed by an RAII preopened-file guard. Carry the returned FUSE handle through MountFS wrapping and File construction, skip the redundant open request, and close the handle on every intermediate failure path. Cache FUSE_CREATE ENOSYS at the connection level and preserve the Linux-compatible MKNOD plus OPEN fallback. Forward Linux-compatible create flags while keeping close, cache-state, writeback, and file-mode initialization consistent with normal FUSE opens. Extend FuseExtended coverage for handle reuse, CREATE flag filtering, ENOSYS fallback caching, and RELEASE/FORGET cleanup of invalid replies. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
f62b190796 |
fix(namespace): make mount propagation transactional (#2116)
* fix(namespace): make mount propagation transactional Prepare every propagation clone, peer/slave registration, and mount edge capacity before publishing topology changes. Preserve the prepared root wrapper and exact covering mount so tuck-under rollback restores stacks, backlinks, flags, and edge counts without allocating. Resolve skipped slave layers through exact mount and peer-group identities to match Linux propagation semantics. Split move propagation into prepare, commit, and abort phases, retain the old edge for allocation-free rollback, and reserve private destination edges before detaching the source. Add kernel coverage for skipped peer/slave sources, move prepare abort, and exact tuck-under restoration. Extend the move dunitest to verify that propagated moves retain their complete child mount subtree. Signed-off-by: longjin <longjin@dragonos.org> * fix(namespace): track latest propagated peer source Update each peer-group source after a successful propagation clone so slaves of uncovered peers inherit from the nearest materialized peer, matching Linux propagate_one() last_source semantics. Add a regression test for the skipped-peer topology and apply the repository formatter required by the architecture format checks. Signed-off-by: longjin <longjin@dragonos.org> * fix(vfs): satisfy mount clippy checks Remove two redundant references in the prepared cover attach and rollback paths so the x86_64 CI lint gate accepts the transactional mount implementation. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
24da4c5cdb |
perf(virtiofs): optimize non-DAX cached reads (#2117)
* perf(virtiofs): optimize non-DAX cached reads Signed-off-by: longjin <longjin@dragonos.org> * fix(virtiofs): complete non-DAX read fault handling Signed-off-by: longjin <longjin@dragonos.org> * fix(vfs): preserve selected mounts across file operations Signed-off-by: longjin <longjin@dragonos.org> * test(virtiofs): add cross-environment performance evidence Signed-off-by: longjin <longjin@dragonos.org> * docs(virtiofs): refresh final validation revisions Signed-off-by: longjin <longjin@dragonos.org> * test(vfs): use mmap-capable fs for mount identity coverage Signed-off-by: longjin <longjin@dragonos.org> * docs(virtiofs): record direct P0 P1 acceptance Signed-off-by: longjin <longjin@dragonos.org> * chore(virtiofs): keep planning documents local Remove documentation-only changes from the pull request while retaining the implementation, tests, and benchmark tooling. Signed-off-by: longjin <longjin@dragonos.org> * fix(virtiofs): validate Linux trace inputs independently Reject an invalid run ID, case ID, file size, or block size even when the paired value is valid. Add negative coverage for every independently validated input. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
d1d6328081 |
refactor(namespace): convert propagation to directory module (#2115)
Move propagation.rs to propagation/mod.rs, adopting Rust's directory module convention consistent with other complex modules in the codebase. No functional changes. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
90f3fc6ba2 |
refactor(namespace): split mount propagation module (#2114)
Separate peer-group management, per-mount propagation state, recursive type changes, topology event handling, and white-box tests into focused modules behind the existing facade. Encapsulate fallible propagation snapshots and peer registry transaction updates so recursive changes preserve allocation failure atomicity, lifecycle lock ordering, Weak mount ownership, and lock-external group release semantics. Update the stale white-box propagation test to exercise the current prepare, topology publication, and commit sequence without changing production behavior or test expectations. Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
33681d8e9f |
fix(namespace): make recursive propagation changes atomic (#2112)
Prepare recursive propagation changes as an explicit transaction while holding the mount lifecycle lock. Snapshot the target subtree and all affected peer, master, and slave relationships, reserve fallible resources up front, simulate Linux propagation semantics privately, and publish only fully prepared final state. Match Linux 6.6 behavior for DFS mount traversal, next-peer ring selection, exact mount-root identity, and slave-list rewiring. Keep group ID release allocation-free with IDA-backed hole tracking and avoid full-graph scans by maintaining direct slave adjacency. Add deterministic failure-path coverage and DragonOS guest tests for recursive propagation semantics, atomic mountinfo snapshots, namespace copying, and concurrent topology changes. Fixes #2098 Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
74e8319a1a |
fix(vfs): replace pathname mount topology (#2111)
* fix(vfs): replace pathname mount topology Replace the pathname-indexed mount model with shared dentry identities and exact mount-object edges. Preserve ordered stacked mounts while making bind, recursive bind, move, unmount, pivot_root, namespace copy, and propagation operate on object topology. Serialize topology publication and lifecycle transitions, preserve locked-mount and shared/slave semantics, and make proc mount exports collect a chroot-aware topology snapshot before rendering filesystem metadata outside topology locks. Give each FUSE node incarnation a stable VFS cache identity so node replacement cannot reuse a stale dentry, while retaining daemon generations for protocol and open-handle validation. Add focused dunitest coverage for rename plus recursive bind, hardlink aliases, chroot visibility, deep slave unmount, stacked move, and pivot_root behavior. Fixes: #1978 Signed-off-by: longjin <longjin@dragonos.org> * fix(vfs): preserve layered and locked mount semantics Introduce lazy dentry mutation commit and per-directory child gates so layered filesystems can perform copy-up without lock-order inversions or negative-alias races. Track detached locked mount components until their final path pin is released, reject ordinary unmount of non-empty mount trees, and mirror Linux propagation unlock semantics for corresponding roots. Cover mounted descendants, cross-user-namespace locked copies, and lazy-detached locked propagation subtrees with dunit regressions. Signed-off-by: longjin <longjin@dragonos.org> * fix(vfs): align recursive bind source filtering Filter recursive bind children against the selected source dentry view before applying unbindable mount semantics, matching Linux copy_tree ordering. This prevents an unrelated locked, unbindable sibling mount from incorrectly rejecting an otherwise valid recursive bind while preserving EPERM for locked mounts inside the copied view.\n\nAdd dunit coverage for the in-view security rejection, the out-of-view sibling case, and MS_MOVE rejection into a mount's own descendant with ELOOP and unchanged topology. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
772fa84fd7 |
fix(vfs): recycle mount propagation group IDs (#2109)
* fix(vfs): recycle mount propagation group IDs Replace monotonic propagation group allocation with reference-counted group ownership and an ID allocator that safely reuses IDs after the last live or pending owner leaves. Validate propagation-change flags before truncation, preflight ordinary and move propagation under the topology lock, preserve shared-slave master hierarchy, and centralize teardown of peer/master/slave relationships. Extend mount propagation coverage for strict flag validation and group ID lifetime semantics. Fixes: #2097 Signed-off-by: longjin <longjin@dragonos.org> * fix(signal): preserve pending group-stop events Use the persistent job-control stop state when reporting natural-child wait events instead of gating them on the scheduler's transient task state. Snapshot and optionally consume both natural and ptraced stop events under the shared sighand lock so WNOWAIT and concurrent SIGCONT cannot mix event generations. Serialize asynchronous stop/continue scheduler transitions with STOP_MASK updates, suppress duplicate notifications, and clear stale job-control events when group exit starts. This matches Linux 6.6 wait_task_stopped(), signal_set_stop_flags(), and do_group_exit() semantics. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |
||
|
|
14606afc42 |
test(virtiofs): add DAX correctness and benchmark gates (#2108)
* test(virtiofs): add DAX correctness and benchmark gates Add low-overhead lifecycle counters for DAX mapping creation, confirmed removal, pressure reclaim, and successful device reset. Extend the DragonOS DAX suite to assert mapping balance, pressure reclaim, and teardown reset behavior. Introduce a fail-fast host preflight that realizes the experimental DAX-capable QEMU device, binds the validated binaries and parameters to a stamp, and verifies the live production virtiofsd process, argv, and socket before boot. Keep the ordinary non-DAX backend path unchanged. Add benchmark always/never path assertions and record the selected DAX expectation so diagnostic runs can gate separate uninstrumented performance runs. Signed-off-by: longjin <longjin@dragonos.org> * fix(virtiofs): preserve DAX overrides across sudo Forward one-shot DAX cache and backend attestation settings when the virtiofsd launcher elevates to root. Preserve the matching virtiofsd binary, cache policy, and extra arguments as well, then restore all explicit overrides after loading env.sh so the production backend remains identical to the preflight configuration. Signed-off-by: longjin <longjin@dragonos.org> --------- Signed-off-by: longjin <longjin@dragonos.org> |